apollo-server-micro: response is missing header 'access-control-allow-methods: POST'

Viewed 1585

In my next.js app I am trying to configure the Apollo Endpoint:

import { ApolloServer, gql } from "apollo-server-micro";

// This data will be returned by our test endpoint. Not sure if I need id? https://apuyou.io/blog/serverless-graphql-apollo-server-nextjs
const tacos = {
  meat: [
    {
      type: 'Al Pastor',
      imgURL: 'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/190130-tacos-al-pastor-horizontal-1-1549571422.png?crop=0.668xw:1.00xh;0.175xw,0&resize=480:*'
    },
    {
      type: 'Barbacoa',
      imgURL: 'https://i2.wp.com/www.downshiftology.com/wp-content/uploads/2021/02/Barbacoa-Tacos-3.jpg'
    },
    {
      type: 'Chorizo',
      imgURL: 'https://www.seriouseats.com/thmb/-8LIIIObcZMUBy-9gXlMsHcaeMI=/610x458/filters:fill(auto,1)/__opt__aboutcom__coeus__resources__content_migration__serious_eats__seriouseats.com__recipes__images__2014__04__20140428-sloppy-joe-chorizo-taco-recipe-food-lab-lite-8-503212a07b0a4d499952ff40aed57694.jpg'
    },
  ],
  fish: [
    {
      type: 'Camaron',
      imgURL: 'https://juegoscocinarpasteleria.org/wp-content/uploads/2019/07/1563435179_315_Tacos-De-Camarones-Con-Crema-De-Cal-Y-Cilantro.jpg'
    },
    {
      type: 'Salmon',
      imgURL: 'https://www.cookingclassy.com/wp-content/uploads/2015/04/salmon-tacos-with-avocado-salsa4-srgb..jpg'
    },
    {
      type: 'Pulpo',
      imgURL: 'https://images.squarespace-cdn.com/content/v1/5710a8b3e707ebb8c58fea2c/1590075315244-QNXQE1LGPH06HV3EDF6B/tacos_34.jpg?format=1000w'
    },
  ],
  veggi: [
    {
      type: 'Cauliflower',
      imgURL: 'https://minimalistbaker.com/wp-content/uploads/2017/07/DELICIOUS-Roasted-Cauliflower-Tacos-with-Adobo-Romesco-30-min-healthy-SO-flavorful-vegan-glutenfree-plantbased-cauliflower-tacos-recipe-8.jpg'
    },
    {
      type: 'Avocado',
      imgURL: 'https://www.ambitiouskitchen.com/wp-content/uploads/2018/03/tacos.jpg'
    },
    {
      type: 'Tofu',
      imgURL: 'http://www.fromachefskitchen.com/wp-content/uploads/2016/08/Tofu-and-Black-Bean-Tacos.jpg'
    },
  ],
}

const typeDefs = gql`
  type Taco {
    type: String
    imgURL: String
  }

  type Query {
    tacos: [Taco]
  }
`;

const resolvers = {
  Query: {
    tacos: () => {
      return tacos;
    },
  },
};

const apolloServer = new ApolloServer({ typeDefs, resolvers });
module.exports = apolloServer.start().then(() => apolloServer.createHandler({path: '/api/graphql',}));


export const config = {
  api: {
    bodyParser: false,
  },
};

However, http://localhost:3000/api/graphql gets me to Apollo Studio Start Page. When I finally get to explorer, I get the error message, that my server can't be reached: OPTIONS response is missing header access-control-allow-methods: POST. I tried to add cors ApolloServer, but with no success. That is my first time trying to get graphql endpoint work in Next.js API, I am pretty lost, what is wrong.

4 Answers

Not sure if you solved it already but I had the same issue. Even with the latest update in next.js examples docs it still gave me this error. So with a little google searching i solved it like this:

const apolloServer = new ApolloServer({ typeDefs, resolvers });

const startServer = apolloServer.start();

export default async function handler(req, res) {
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader(
        "Access-Control-Allow-Origin",
        "https://studio.apollographql.com"
    );
    res.setHeader(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Access-Control-Allow-Headers"
    );
    res.setHeader(
        "Access-Control-Allow-Methods",
        "POST, GET, PUT, PATCH, DELETE, OPTIONS, HEAD"
    );
    if (req.method === "OPTIONS") {
        res.end();
        return false;
    }

    await startServer;
    await apolloServer.createHandler({
        path: "/api/graphql",
    })(req, res);
}

With help of George Vlassis's answer I post here only needed headers for working Apollo Explorer:

res.setHeader(
  'Access-Control-Allow-Origin',
  'https://studio.apollographql.com',
);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Headers', ' Content-Type');

If you're using Apollo-server-Micro, then you can make use of micro-cors:

yarn add micro-cors

Then, remember to import micro_cors not micro-cors:

import micro_cors from "micro-cors"

const cors = micro_cors({
origin: "https://studio.apollographql.com",
allowCredentials:true,
allowMethods:["GET", "POST","PUT","DELETE"],
allowHeaders:["access-control-allow-credentials","access-control-allow-origin","content-type"]          
})

Afterwards, wrap this with function:

const handlers= cors(async  function  handlers(req: NextApiRequest, res:   NextApiResponse) {
await startServer

if (req.method === "OPTIONS") {
    res.end()
    return false
}

await apolloserver.createHandler({ path: "/api/graphql" })(req, res);
})

export default handlers

If you diagnose the endpoint by this:

npx diagnose-endpoint@1.1.0 --endpoint=http://localhost:3000/api/graphql

And get the result as this:

Diagnosing http://localhost:3000/api/graphql
⚠️  OPTIONS response is missing header 'access-control-allow-methods: POST'

Just set the api.bodyParser to false and put it as a config constant at the bottom of your graphql server api file like this:

import type { NextApiRequest, NextApiResponse } from "next";
import { gql, ApolloServer } from "apollo-server-micro";
import { ApolloServerPluginLandingPageGraphQLPlayground } from "apollo-server-core";

...

const apolloServer = new ApolloServer({
    typeDefs,
    resolvers,
    plugins: [ApolloServerPluginLandingPageGraphQLPlayground()],
});

const startServer = apolloServer.start();

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
): Promise<void> {
  await startServer;
  await apolloServer.createHandler({
    path: "/api/graphql",
  })(req, res);
}

export const config = {
  api: {
    bodyParser: false,
  },
};
Related