Skip to content

Commit d8594d2

Browse files
Allow CORS headers to be customizable via config
1 parent e94a260 commit d8594d2

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

src/index.js

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,27 @@ const setCors = require('./utils/setCors')
55
const graphQLOptions = {
66
// Set the path for the GraphQL server
77
baseEndpoint: '/',
8+
89
// Set the path for the GraphQL playground
910
// This option can be removed to disable the playground route
1011
playgroundEndpoint: '/___graphql',
12+
1113
// When a request's path isn't matched, forward it to the origin
1214
forwardUnmatchedRequestsToOrigin: false,
15+
1316
// Enable debug mode to return script errors directly in browser
1417
debug: false,
18+
19+
// Enable CORS headers on GraphQL requests
20+
// Set to `true` for defaults (see `utils/setCors`),
21+
// or pass an object to configure each header
22+
cors: true,
23+
// cors: {
24+
// allowCredentials: 'true',
25+
// allowHeaders: 'Content-type',
26+
// allowOrigin: '*',
27+
// allowMethods: 'GET, POST, PUT',
28+
// },
1529
}
1630

1731
const handleRequest = request => {
@@ -22,7 +36,9 @@ const handleRequest = request => {
2236
request.method === 'OPTIONS'
2337
? new Response('', { status: 204 })
2438
: await apollo(request, graphQLOptions)
25-
setCorsHeaders(response)
39+
if (graphQLOptions.cors) {
40+
setCors(response, graphQLOptions.cors)
41+
}
2642
return response
2743
} else if (
2844
graphQLOptions.playgroundEndpoint &&

src/utils/setCors.js

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,19 @@
1-
const setCorsHeaders = response => {
2-
response.headers.set('Access-Control-Allow-Origin', '*')
3-
response.headers.set('Access-Control-Allow-Credentials', 'true')
4-
response.headers.set('Access-Control-Allow-Methods', 'GET,POST')
5-
response.headers.set('Access-Control-Allow-Headers', 'application/json, Content-type')
1+
const setCorsHeaders = (response, config) => {
2+
const corsConfig = config instanceof Object ? config : false
3+
4+
response.headers.set(
5+
'Access-Control-Allow-Credentials',
6+
corsConfig ? corsConfig.allowCredentials : 'true',
7+
)
8+
response.headers.set(
9+
'Access-Control-Allow-Headers',
10+
corsConfig ? corsConfig.allowHeaders : 'application/json, Content-type',
11+
)
12+
response.headers.set(
13+
'Access-Control-Allow-Methods',
14+
corsConfig ? corsConfig.allowMethods : 'GET, POST',
15+
)
16+
response.headers.set('Access-Control-Allow-Origin', corsConfig ? corsConfig.allowOrigin : '*')
617
response.headers.set('X-Content-Type-Options', 'nosniff')
718
}
819

0 commit comments

Comments
 (0)