I am having a hard time to make CORS work with next.js API routes and "apollo-server-micro".
I put together this sample repo to reproduce the issue:
https://github.com/sakhmedbayev/nextjs-graphql-example
My goal is to make the graphql API route - "apollo-server-micro" (http://localhost:3000/api/graphql) to be accessible from all origins, e.g., http://localhost:3000, http://subdomain.localhost:3000, or http://localhost:5000
I would greatly appreciate any help!
im having issue implementing this as well
Hey, combined some ideas from the repo @sakhmedbayev posted as well as https://github.com/apollographql/apollo-server/issues/2473 and came up with:
import { ApolloServer, gql } from 'apollo-server-micro';
import Cors from 'micro-cors';
const cors = Cors();
// This data will be returned by our test endpoint
const products = [
{
_id: 1,
name: 'Cookie',
price: 300,
},
{
_id: 2,
name: 'Brownie',
price: 350,
},
];
// Construct a schema using GraphQL schema language
const typeDefs = gql`
type Product {
_id: ID
name: String
price: Int
}
type Query {
products: [Product]
}
`;
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
products: () => products,
},
};
const server = new ApolloServer({ typeDefs, resolvers });
export default cors((req, res) => {
if (req.method === 'OPTIONS') {
res.end();
return false;
}
return server.createHandler({
path: '/api/graphql',
})(req, res);
});
export const config = {
api: {
bodyParser: false,
},
};
Let me know if this works for you
If the CORS example in the README.md for the apollo-server-micro package doesn't work (which is published to npm), please open a PR that adjusts it!
i can confirm the example works. thanks
Most helpful comment
Hey, combined some ideas from the repo @sakhmedbayev posted as well as https://github.com/apollographql/apollo-server/issues/2473 and came up with:
Let me know if this works for you