Apollo-server: micro: CORS' OPTIONS not implemented.

Created on 20 Mar 2019  ยท  4Comments  ยท  Source: apollographql/apollo-server

In the apollo-server-micro package, the CORS example is incorrect because Apollo Server will respond with status code 405 for OPTIONS requests. To avoid this, a simple fix is to use the following code instead:

module.exports = cors((req, res) => {
  if (req.method === 'OPTIONS') {
    res.end()
    return
  }
  return server.createHandler()(req, res)
})
๐Ÿ–‡๏ธ micro ๐Ÿ™ help-wanted

Most helpful comment

Just a heads up for anyone else who stumbles across this problem. Here is the code that worked for my server.

import micro from 'micro';
import cors from 'micro-cors';
import { ApolloServer } from 'apollo-server-micro';

const server = new ApolloServer({/* config */});

const optionsHandler = (req: IncomingMessage, res: ServerResponse) => {
  if (req.method === 'OPTIONS') {
    res.end();
    return;
  }
  return server.createHandler()(req, res);
};
const microserver = micro(cors()(optionsHandler));
export default microserver.listen({ port: config.port }, () => {
  const plaground = server.graphqlPath;
  console.log(`๐Ÿ‘‰  Server: http://localhost:${config.port}${plaground}`);
  console.log(`๐Ÿ‘‰  Environment: ${config.environment}`);
  console.log(`๐Ÿ‘‰  Production: ${config.production}`);
});

Hope it helps!

All 4 comments

I think this would be better fixed in the implementation rather than a docs change. This was fixed in the lambda implementation here:

https://github.com/apollographql/apollo-server/blob/5b46e44451094c4daae3022f40347e234225a7de/packages/apollo-server-lambda/src/ApolloServer.ts#L151-L161

Just a heads up for anyone else who stumbles across this problem. Here is the code that worked for my server.

import micro from 'micro';
import cors from 'micro-cors';
import { ApolloServer } from 'apollo-server-micro';

const server = new ApolloServer({/* config */});

const optionsHandler = (req: IncomingMessage, res: ServerResponse) => {
  if (req.method === 'OPTIONS') {
    res.end();
    return;
  }
  return server.createHandler()(req, res);
};
const microserver = micro(cors()(optionsHandler));
export default microserver.listen({ port: config.port }, () => {
  const plaground = server.graphqlPath;
  console.log(`๐Ÿ‘‰  Server: http://localhost:${config.port}${plaground}`);
  console.log(`๐Ÿ‘‰  Environment: ${config.environment}`);
  console.log(`๐Ÿ‘‰  Production: ${config.production}`);
});

Hope it helps!

PR welcome!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

veeramarni picture veeramarni  ยท  3Comments

disyam picture disyam  ยท  3Comments

danilobuerger picture danilobuerger  ยท  3Comments

manuelfink picture manuelfink  ยท  3Comments

dobesv picture dobesv  ยท  3Comments