Skip to content

Commit

Permalink
Merge pull request #9 from signalnerve/kristian/cors
Browse files Browse the repository at this point in the history
Add CORS support for GraphQL requests
  • Loading branch information
kristianfreeman authored Aug 19, 2019
2 parents 0b6db7c + d8594d2 commit 40dcc81
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,45 @@
const apollo = require('./handlers/apollo')
const playground = require('./handlers/playground')
const setCors = require('./utils/setCors')

const graphQLOptions = {
// Set the path for the GraphQL server
baseEndpoint: '/',

// Set the path for the GraphQL playground
// This option can be removed to disable the playground route
playgroundEndpoint: '/___graphql',

// When a request's path isn't matched, forward it to the origin
forwardUnmatchedRequestsToOrigin: false,

// Enable debug mode to return script errors directly in browser
debug: false,

// Enable CORS headers on GraphQL requests
// Set to `true` for defaults (see `utils/setCors`),
// or pass an object to configure each header
cors: true,
// cors: {
// allowCredentials: 'true',
// allowHeaders: 'Content-type',
// allowOrigin: '*',
// allowMethods: 'GET, POST, PUT',
// },
}

const handleRequest = request => {
const url = new URL(request.url)
try {
if (url.pathname === graphQLOptions.baseEndpoint) {
return apollo(request, graphQLOptions)
const response =
request.method === 'OPTIONS'
? new Response('', { status: 204 })
: await apollo(request, graphQLOptions)
if (graphQLOptions.cors) {
setCors(response, graphQLOptions.cors)
}
return response
} else if (
graphQLOptions.playgroundEndpoint &&
url.pathname === graphQLOptions.playgroundEndpoint
Expand Down
20 changes: 20 additions & 0 deletions src/utils/setCors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const setCorsHeaders = (response, config) => {
const corsConfig = config instanceof Object ? config : false

response.headers.set(
'Access-Control-Allow-Credentials',
corsConfig ? corsConfig.allowCredentials : 'true',
)
response.headers.set(
'Access-Control-Allow-Headers',
corsConfig ? corsConfig.allowHeaders : 'application/json, Content-type',
)
response.headers.set(
'Access-Control-Allow-Methods',
corsConfig ? corsConfig.allowMethods : 'GET, POST',
)
response.headers.set('Access-Control-Allow-Origin', corsConfig ? corsConfig.allowOrigin : '*')
response.headers.set('X-Content-Type-Options', 'nosniff')
}

module.exports = setCorsHeaders

0 comments on commit 40dcc81

Please sign in to comment.