Skip to content

Commit

Permalink
Allow CORS headers to be customizable via config
Browse files Browse the repository at this point in the history
  • Loading branch information
kristianfreeman committed Aug 19, 2019
1 parent e94a260 commit d8594d2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
18 changes: 17 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,27 @@ 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 => {
Expand All @@ -22,7 +36,9 @@ const handleRequest = request => {
request.method === 'OPTIONS'
? new Response('', { status: 204 })
: await apollo(request, graphQLOptions)
setCorsHeaders(response)
if (graphQLOptions.cors) {
setCors(response, graphQLOptions.cors)
}
return response
} else if (
graphQLOptions.playgroundEndpoint &&
Expand Down
21 changes: 16 additions & 5 deletions src/utils/setCors.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
const setCorsHeaders = response => {
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Credentials', 'true')
response.headers.set('Access-Control-Allow-Methods', 'GET,POST')
response.headers.set('Access-Control-Allow-Headers', 'application/json, Content-type')
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')
}

Expand Down

0 comments on commit d8594d2

Please sign in to comment.