Skip to content

fix: add missing data to middleware request object #1634

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

Merged
merged 7 commits into from
Sep 28, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ aware that this will result in slower performance, as all pages that match middl

For more details on Next.js Middleware with Netlify, see the [middleware docs](https://github.com/netlify/next-runtime/blob/main/docs/middleware.md).

### Limitations

Due to how the site configuration is handled when it's run using Netlify Edge Functions, data such as `locale` and `defaultLocale` will be missing on the `req.nextUrl` object when running `netlify dev`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When you say "such as", does that mean there are other things missing?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't yet done an audit of all the properties that are affected by this so I'm not 100% certain that these are the only properties affected on the nextUrl object.

Something to add here as well but the pathname (as reported by the user who originally raised this issue with us) was also incorrect before these changes and should be mentioned.


However, this data is available on `req.nextUrl` in a production environment.

## Monorepos

If you are using a monorepo you will need to change `publish` to point to the full path to the built `.next` directory,
Expand Down
2 changes: 2 additions & 0 deletions jestSetup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// eslint-disable-next-line n/no-unpublished-require
require('jest-fetch-mock').enableMocks()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without this package and setup, the Request and Headers objects aren't found in the context of the test file that was added (request.spec.ts)

87 changes: 69 additions & 18 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"eslint-plugin-unicorn": "^43.0.2",
"husky": "^7.0.4",
"jest": "^27.0.0",
"jest-fetch-mock": "^3.0.3",
"netlify-plugin-cypress": "^2.2.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.1.2",
Expand All @@ -81,6 +82,9 @@
"node": ">=16.0.0"
},
"jest": {
"setupFiles": [
"./jestSetup.js"
],
"testMatch": [
"**/test/**/*.js",
"**/test/**/*.ts",
Expand All @@ -106,4 +110,4 @@
"demos/custom-routes",
"demos/next-with-edge-functions"
]
}
}
2 changes: 1 addition & 1 deletion packages/next/src/middleware/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export class MiddlewareRequest extends Request {
}

get nextUrl() {
return this.nextRequest.url
return this.nextRequest.nextUrl
}

get url() {
Expand Down
118 changes: 118 additions & 0 deletions packages/next/test/request.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import Chance from 'chance'
import { NextURL } from 'next/dist/server/web/next-url'
import { NextCookies } from 'next/dist/server/web/spec-extension/cookies'
import { NextRequest } from 'next/server'
import { MiddlewareRequest } from '../src/middleware/request'

const chance = new Chance()

describe('MiddlewareRequest', () => {
let nextRequest, mockHeaders, mockHeaderValue, requestId, geo, ip, url

beforeEach(() => {
globalThis.Deno = {}
globalThis.NFRequestContextMap = new Map()

ip = chance.ip()
url = chance.url()

const context = {
geo: {
country: {
code: '',
},
subdivision: {
code: '',
},
city: '',
},
ip,
}

geo = {
country: context.geo.country?.code,
region: context.geo.subdivision?.code,
city: context.geo.city,
}

const req = new URL(url)

requestId = chance.guid()
globalThis.NFRequestContextMap.set(requestId, {
request: req,
context,
})

mockHeaders = new Headers()
mockHeaderValue = chance.word()

mockHeaders.append('foo', mockHeaderValue)
mockHeaders.append('x-nf-request-id', requestId)

const request = {
headers: mockHeaders,
geo,
method: 'GET',
ip: context.ip,
body: null,
}

nextRequest = new NextRequest(req, request)
})

afterEach(() => {
nextRequest = null
requestId = null
delete globalThis.Deno
delete globalThis.NFRequestContextMap
})

it('throws an error when MiddlewareRequest is run outside of edge environment', () => {
delete globalThis.Deno
expect(() => new MiddlewareRequest(nextRequest)).toThrowError(
'MiddlewareRequest only works in a Netlify Edge Function environment',
)
})

it('throws an error when x-nf-request-id header is missing', () => {
nextRequest.headers.delete('x-nf-request-id')
expect(() => new MiddlewareRequest(nextRequest)).toThrowError('Missing x-nf-request-id header')
})

it('throws an error when request context is missing', () => {
globalThis.NFRequestContextMap.delete(requestId)
expect(() => new MiddlewareRequest(nextRequest)).toThrowError(
`Could not find request context for request id ${requestId}`,
)
})

it('returns the headers object', () => {
const mwRequest = new MiddlewareRequest(nextRequest)
expect(mwRequest.headers).toStrictEqual(mockHeaders)
})

it('returns the cookies object', () => {
const mwRequest = new MiddlewareRequest(nextRequest)
expect(mwRequest.cookies).toBeInstanceOf(NextCookies)
})

it('returns the geo object', () => {
const mwRequest = new MiddlewareRequest(nextRequest)
expect(mwRequest.geo).toStrictEqual(geo)
})

it('returns the ip object', () => {
const mwRequest = new MiddlewareRequest(nextRequest)
expect(mwRequest.ip).toStrictEqual(ip)
})

it('returns the nextUrl object', () => {
const mwRequest = new MiddlewareRequest(nextRequest)
expect(mwRequest.nextUrl).toBeInstanceOf(NextURL)
})

it('returns the url', () => {
const mwRequest = new MiddlewareRequest(nextRequest)
expect(mwRequest.url).toEqual(url)
})
})
7 changes: 7 additions & 0 deletions packages/runtime/src/helpers/edge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { copy, copyFile, emptyDir, ensureDir, readJSON, readJson, writeJSON, wri
import type { MiddlewareManifest } from 'next/dist/build/webpack/plugins/middleware-plugin'
import type { RouteHas } from 'next/dist/lib/load-custom-routes'

import { getRequiredServerFiles } from './config'

// This is the format as of [email protected]
interface EdgeFunctionDefinitionV1 {
env: string[]
Expand Down Expand Up @@ -198,6 +200,11 @@ export const writeEdgeFunctions = async (netlifyConfig: NetlifyConfig) => {

await copy(getEdgeTemplatePath('../edge-shared'), join(edgeFunctionRoot, 'edge-shared'))

const { publish } = netlifyConfig.build
const nextConfigFile = await getRequiredServerFiles(publish)
const nextConfig = nextConfigFile.config
await writeJSON(join(edgeFunctionRoot, 'edge-shared', 'nextConfig.json'), nextConfig)

if (!process.env.NEXT_DISABLE_EDGE_IMAGES) {
console.log(
'Using Netlify Edge Functions for image format detection. Set env var "NEXT_DISABLE_EDGE_IMAGES=true" to disable.',
Expand Down
Empty file.
Loading