1

I'll do my best to explain my issue.

I'm building a NextJS site and using Apollo to handle Graph QL, and it's been working perfectly fine when I test the API using Postman, but when I try to run in dev I get CORS errors:

This operation has been blocked as a potential Cross-Site Request Forgery (CSRF). Please either specify a 'content-type' header (with a type that is not one of application/x-www-form-urlencoded, multipart/form-data, text/plain) or provide a non-empty value for one of the following headers: x-apollo-operation-name, apollo-require-preflight

This is my code that runs the Apollo code.

index.ts:

import { ApolloServer } from '@apollo/server';
import { startServerAndCreateNextHandler } from '@as-integrations/next';
import { applyMiddleware } from 'graphql-middleware';
import { makeExecutableSchema } from '@graphql-tools/schema';

import { getUserFromToken } from './../../../server/security/jwt';
import typeDefs from './schema';

import { resolvers } from './resolvers';
import { permissions } from './permissions';

const schema = applyMiddleware(
    makeExecutableSchema({
        typeDefs: typeDefs,
        resolvers,
    }),
    permissions
);

const server = new ApolloServer({
    schema,
    includeStacktraceInErrorResponses: false,
});

export default startServerAndCreateNextHandler(server, {
    context: async (req, res) => {
        const cookies = req.cookies;
        const token = cookies.titanAuthToken || '';
        var user;
        if (token) {
            user = getUserFromToken(token);
        }

        return { req, res, user, token };
    },
});

I have tried a few suggestions from google including this:

const server = new ApolloServer({
    schema,
    includeStacktraceInErrorResponses: false,
    cors: {
        origin: true,
        credentials: true, // true if you need cookies/authentication
        methods: ['GET', 'POST', 'OPTIONS'],
    }
});

But when I try the above I get this error:

Argument of type '{ schema: GraphQLSchemaWithFragmentReplacements; includeStacktraceInErrorResponses: false; cors: { origin: boolean; credentials: boolean; methods: string[]; }; }' is not assignable to parameter of type 'ApolloServerOptions<BaseContext>'.
  Object literal may only specify known properties, and 'cors' does not exist in type 'ApolloServerOptionsWithSchema<BaseContext>

Any help to fix this CORS error would be greatly appreciated.

  • 1
    Does this answer your question? [Next JS Blocked by CORS: Does not have HTTP ok status](https://stackoverflow.com/questions/67645903/next-js-blocked-by-cors-does-not-have-http-ok-status) – Dan Crews Jan 06 '23 at 22:08
  • Apollo doesn't solve cors for you anymore. You'll need to handle cors yourself in a wrapper around what is currently your default export. [See here](https://stackoverflow.com/a/67646272/652728) – Dan Crews Jan 06 '23 at 22:09
  • Thanks @DanCrews I'll try that out and let you know how I go. – Alex Sorensen Jan 08 '23 at 23:46

0 Answers0