Handling CORS in GraphQL
For GraphQL endpoints, the CORS configuration is similar to REST APIs, but you might need to handle OPTIONS requests specifically for preflight checks.
const corsOptions = {
origin: 'http://example.com',
methods: 'GET,POST,OPTIONS',
allowedHeaders: 'Content-Type,Authorization',
};
app.use('/graphql', cors(corsOptions), graphqlHTTP({
schema: yourGraphQLSchema,
rootValue: root,
graphiql: true,
}));
CORS with WebSockets
CORS is not applicable to WebSockets directly, but you should ensure that WebSocket connections are secured and only accepted from trusted origins. You may need to handle CORS settings in the HTTP upgrade requests that initiate the WebSocket connection.
Leave a Reply