Skip to content

Commit

Permalink
fix(cors): add content-length: 0 header if 204 is returned by OPTIONS…
Browse files Browse the repository at this point in the history
… request (#2239)

* fix(cors): add content-length: 0 header if 204 is returned by OPTIONS request

* add changeset
  • Loading branch information
davidruisinger committed Dec 21, 2022
1 parent c152105 commit d295878
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/slimy-kings-confess.md
@@ -0,0 +1,5 @@
---
'graphql-yoga': patch
---

Add content-length: 0 header if 204 is returned by OPTIONS request
6 changes: 6 additions & 0 deletions packages/graphql-yoga/src/plugins/useCORS.ts
Expand Up @@ -146,6 +146,12 @@ export function useCORS<TServerContext extends Record<string, any>>(
if (request.method.toUpperCase() === 'OPTIONS') {
const response = new fetchAPI.Response(null, {
status: 204,
// Safari (and potentially other browsers) need content-length 0,
// for 204 or they just hang waiting for a body
// see: https://github.com/expressjs/cors/blob/master/lib/index.js#L176
headers: {
'Content-Length': '0',
},
})
endResponse(response)
}
Expand Down
32 changes: 32 additions & 0 deletions packages/graphql-yoga/src/plugins/useCors.spec.ts
@@ -1,7 +1,39 @@
import { Request } from '@whatwg-node/fetch'
import { createSchema } from '../schema.js'
import { createYoga } from '../server.js'
import { YogaInitialContext } from '../types.js'
import { getCORSHeadersByRequestAndOptions, CORSOptions } from './useCORS.js'

describe('CORS', () => {
describe('OPTIONS call', () => {
it('should respond with correct status & headers', async () => {
const schemaFactory = async (ctx: YogaInitialContext) => {
return createSchema({
typeDefs: /* GraphQL */ `
type Query {
foo: String
}
`,
resolvers: {
Query: {
foo: () => 'bar',
},
},
})
}
const yoga = createYoga({
schema: schemaFactory,
})
let result = await yoga.fetch('http://yoga/graphql', {
method: 'OPTIONS',
headers: {
'Content-Type': 'application/json',
},
})
expect(result.status).toEqual(204)
expect(result.headers.get('Content-Length')).toEqual('0')
})
})
describe('No origins specified', () => {
const corsOptionsWithNoOrigins = {}
it('should return the wildcard if no origin is sent with header', () => {
Expand Down

0 comments on commit d295878

Please sign in to comment.