Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bypass OPTIONS handling for API routes #12978

Merged
merged 6 commits into from
May 16, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
"cheerio": "0.22.0",
"clone": "2.1.2",
"cookie": "0.4.1",
"cors": "2.8.5",
"coveralls": "3.0.3",
"cross-env": "6.0.3",
"cross-spawn": "6.0.5",
Expand Down
8 changes: 7 additions & 1 deletion packages/next/server/hot-reloader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import webpack from 'webpack'
import { createEntrypoints, createPagesMapping } from '../build/entries'
import { watchCompilers } from '../build/output'
import getBaseWebpackConfig from '../build/webpack-config'
import { NEXT_PROJECT_ROOT_DIST_CLIENT } from '../lib/constants'
import { NEXT_PROJECT_ROOT_DIST_CLIENT, API_ROUTE } from '../lib/constants'
import { fileExists } from '../lib/file-exists'
import { recursiveDelete } from '../lib/recursive-delete'
import {
Expand Down Expand Up @@ -47,6 +47,12 @@ export async function renderScriptError(res: ServerResponse, error: Error) {
}

function addCorsSupport(req: IncomingMessage, res: ServerResponse) {
const isApiRoute = req.url!.match(API_ROUTE)
// API routes handle their own CORS headers
if (isApiRoute) {
return { preflight: false }
}

if (!req.headers.origin) {
return { preflight: false }
}
Expand Down
32 changes: 32 additions & 0 deletions test/integration/api-support/pages/api/cors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import Cors from 'cors'

// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function initMiddleware(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, result => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}

// Initialize the cors middleware
const cors = initMiddleware(
// You can read more about the available options here: https://github.com/expressjs/cors#configuration-options
Cors({
// Only allow requests with GET, POST and OPTIONS
methods: ['GET', 'POST', 'OPTIONS'],
})
)

export default async function handler(req, res) {
// Run cors
await cors(req, res)

// Rest of the API logic
res.json({ message: 'Hello Everyone!' })
}
11 changes: 11 additions & 0 deletions test/integration/api-support/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ function runTests(dev = false) {
expect(res.status).not.toEqual(404)
})

it('should set cors headers when adding cors middleware', async () => {
const res = await fetchViaHTTP(appPort, '/api/cors', null, {
method: 'OPTIONS',
})
timneutkens marked this conversation as resolved.
Show resolved Hide resolved

expect(res.status).toEqual(204)
expect(res.headers.get('access-control-allow-methods')).toEqual(
'GET,POST,OPTIONS'
)
})

it('should work with index api', async () => {
const text = await fetchViaHTTP(appPort, '/api', null, {}).then(
res => res.ok && res.text()
Expand Down
20 changes: 14 additions & 6 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5518,6 +5518,14 @@ core-util-is@1.0.2, core-util-is@~1.0.0:
resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7"
integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=

cors@2.8.5:
version "2.8.5"
resolved "https://registry.yarnpkg.com/cors/-/cors-2.8.5.tgz#eac11da51592dd86b9f06f6e7ac293b3df875d29"
integrity sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==
dependencies:
object-assign "^4"
vary "^1"

cosmiconfig@^2.1.0, cosmiconfig@^2.1.1:
version "2.2.2"
resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-2.2.2.tgz#6173cebd56fac042c1f4390edf7af6c07c7cb892"
Expand Down Expand Up @@ -11807,7 +11815,7 @@ oauth-sign@~0.9.0:
resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.9.0.tgz#47a7b016baa68b5fa0ecf3dee08a85c679ac6455"
integrity sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==

object-assign@4.1.1, object-assign@^4.0.1, object-assign@^4.1.0, object-assign@^4.1.1:
object-assign@4.1.1, object-assign@^4, object-assign@^4.0.1, object-assign@^4.1.0, object-assign@^4.1.1:
version "4.1.1"
resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863"
integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=
Expand Down Expand Up @@ -16059,10 +16067,10 @@ styled-components@5.1.0:
shallowequal "^1.1.0"
supports-color "^5.5.0"

styled-jsx@3.2.5:
version "3.2.5"
resolved "https://registry.yarnpkg.com/styled-jsx/-/styled-jsx-3.2.5.tgz#0172a3e13a0d6d8bf09167dcaf32cf7102d932ca"
integrity sha512-prEahkYwQHomUljJzXzrFnBmQrSMtWOBbXn8QeEkpfFkqMZQGshxzzp4H8ebBIsbVlHF/3+GSXMnmK/fp7qVYQ==
styled-jsx@3.3.0:
version "3.3.0"
resolved "https://registry.yarnpkg.com/styled-jsx/-/styled-jsx-3.3.0.tgz#32335c1a3ecfc923ba4f9c056eeb3d4699006b09"
integrity sha512-sh8BI5eGKyJlwL4kNXHjb27/a/GJV8wP4ElRIkRXrGW3sHKOsY9Pa1VZRNxyvf3+lisdPwizD9JDkzVO9uGwZw==
dependencies:
"@babel/types" "7.8.3"
babel-plugin-syntax-jsx "6.18.0"
Expand Down Expand Up @@ -17163,7 +17171,7 @@ validate-npm-package-name@3.0.0, validate-npm-package-name@^3.0.0:
dependencies:
builtins "^1.0.3"

vary@~1.1.2:
vary@^1, vary@~1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc"
integrity sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=
Expand Down