Skip to content

Commit 40dcc81

Browse files
Merge pull request #9 from signalnerve/kristian/cors
Add CORS support for GraphQL requests
2 parents 0b6db7c + d8594d2 commit 40dcc81

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

src/index.js

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,45 @@
11
const apollo = require('./handlers/apollo')
22
const playground = require('./handlers/playground')
3+
const setCors = require('./utils/setCors')
34

45
const graphQLOptions = {
56
// Set the path for the GraphQL server
67
baseEndpoint: '/',
8+
79
// Set the path for the GraphQL playground
810
// This option can be removed to disable the playground route
911
playgroundEndpoint: '/___graphql',
12+
1013
// When a request's path isn't matched, forward it to the origin
1114
forwardUnmatchedRequestsToOrigin: false,
15+
1216
// Enable debug mode to return script errors directly in browser
1317
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+
// },
1429
}
1530

1631
const handleRequest = request => {
1732
const url = new URL(request.url)
1833
try {
1934
if (url.pathname === graphQLOptions.baseEndpoint) {
20-
return apollo(request, graphQLOptions)
35+
const response =
36+
request.method === 'OPTIONS'
37+
? new Response('', { status: 204 })
38+
: await apollo(request, graphQLOptions)
39+
if (graphQLOptions.cors) {
40+
setCors(response, graphQLOptions.cors)
41+
}
42+
return response
2143
} else if (
2244
graphQLOptions.playgroundEndpoint &&
2345
url.pathname === graphQLOptions.playgroundEndpoint

src/utils/setCors.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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 : '*')
17+
response.headers.set('X-Content-Type-Options', 'nosniff')
18+
}
19+
20+
module.exports = setCorsHeaders

0 commit comments

Comments
 (0)