Unverified Commit b01a6ba6 authored by Steven's avatar Steven Committed by GitHub

Add TS types for NextMiddleware (#30578)

This allows TypeScript users to have type safety for middleware functions.

- Closes #30490 
Co-authored-by: 's avatarLee Robinson <9113740+leerob@users.noreply.github.com>
Co-authored-by: 's avatarJJ Kasper <22380829+ijjk@users.noreply.github.com>
parent 4410de9f
...@@ -4,19 +4,29 @@ description: Use Middleware to run code before a request is completed. ...@@ -4,19 +4,29 @@ description: Use Middleware to run code before a request is completed.
# next/server # next/server
Middleware is created by using a `middleware` function that lives inside a `_middleware` file. The Middleware API is based upon the native [`FetchEvent`](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent), [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response), and [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) objects. The `next/server` module provides several exports for server-only helpers, such as [Middleware](/docs/middleware.md).
## NextMiddleware
Middleware is created by using a `middleware` function that lives inside a `_middleware` file. The Middleware API is based upon the native [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request), [`FetchEvent`](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent), and [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) objects.
These native Web API objects are extended to give you more control over how you manipulate and configure a response, based on the incoming requests. These native Web API objects are extended to give you more control over how you manipulate and configure a response, based on the incoming requests.
The function signature: The function signature is defined as follows:
```ts ```ts
import type { NextRequest, NextFetchEvent } from 'next/server' type NextMiddlewareResult = NextResponse | Response | null | undefined
export type Middleware = ( type NextMiddleware = (
request: NextRequest, request: NextRequest,
event: NextFetchEvent event: NextFetchEvent
) => Promise<Response | undefined> | Response | undefined ) => NextMiddlewareResult | Promise<NextMiddlewareResult>
```
It can be imported from `next/server` with the following:
```ts
import type { NextMiddleware } from 'next/server'
``` ```
The function can be a default export and as such, does **not** have to be named `middleware`. Though this is a convention. Also note that you only need to make the function `async` if you are running asynchronous code. The function can be a default export and as such, does **not** have to be named `middleware`. Though this is a convention. Also note that you only need to make the function `async` if you are running asynchronous code.
......
export { NextFetchEvent } from 'next/dist/server/web/spec-extension/fetch-event' export { NextFetchEvent } from 'next/dist/server/web/spec-extension/fetch-event'
export { NextRequest } from 'next/dist/server/web/spec-extension/request' export { NextRequest } from 'next/dist/server/web/spec-extension/request'
export { NextResponse } from 'next/dist/server/web/spec-extension/response' export { NextResponse } from 'next/dist/server/web/spec-extension/response'
export { NextMiddleware } from 'next/dist/server/web/types'
import type { RequestData, FetchEventResult } from './types' import type { NextMiddleware, RequestData, FetchEventResult } from './types'
import { DeprecationError } from './error' import { DeprecationError } from './error'
import { fromNodeHeaders } from './utils' import { fromNodeHeaders } from './utils'
import { NextFetchEvent } from './spec-extension/fetch-event' import { NextFetchEvent } from './spec-extension/fetch-event'
...@@ -7,7 +7,7 @@ import { NextResponse } from './spec-extension/response' ...@@ -7,7 +7,7 @@ import { NextResponse } from './spec-extension/response'
import { waitUntilSymbol } from './spec-compliant/fetch-event' import { waitUntilSymbol } from './spec-compliant/fetch-event'
export async function adapter(params: { export async function adapter(params: {
handler: (request: NextRequest, event: NextFetchEvent) => Promise<Response> handler: NextMiddleware
page: string page: string
request: RequestData request: RequestData
}): Promise<FetchEventResult> { }): Promise<FetchEventResult> {
......
...@@ -73,7 +73,7 @@ export class NextResponse extends Response { ...@@ -73,7 +73,7 @@ export class NextResponse extends Response {
}) })
} }
static redirect(url: string | NextURL, status = 302) { static redirect(url: string | NextURL | URL, status = 302) {
if (!REDIRECTS.has(status)) { if (!REDIRECTS.has(status)) {
throw new RangeError( throw new RangeError(
'Failed to execute "redirect" on "response": Invalid status code' 'Failed to execute "redirect" on "response": Invalid status code'
......
import type { I18NConfig } from '../config-shared' import type { I18NConfig } from '../config-shared'
import type { NextRequest } from '../web/spec-extension/request'
import type { NextFetchEvent } from '../web/spec-extension/fetch-event'
import type { NextResponse } from './spec-extension/response'
export interface NodeHeaders { export interface NodeHeaders {
[header: string]: string | string[] | undefined [header: string]: string | string[] | undefined
...@@ -31,3 +34,10 @@ export interface FetchEventResult { ...@@ -31,3 +34,10 @@ export interface FetchEventResult {
response: Response response: Response
waitUntil: Promise<any> waitUntil: Promise<any>
} }
export type NextMiddlewareResult = NextResponse | Response | null | undefined
export type NextMiddleware = (
request: NextRequest,
event: NextFetchEvent
) => NextMiddlewareResult | Promise<NextMiddlewareResult>
module.exports = {
i18n: {
locales: ['en', 'fr', 'nl'],
defaultLocale: 'en',
},
}
export default function Index() {
return <p className="title">Dynamic route</p>
}
import { NextMiddleware } from 'next/server'
export const middleware: NextMiddleware = function (request) {
return new Response(null, {
headers: {
'req-url-basepath': request.nextUrl.basePath,
'req-url-pathname': request.nextUrl.pathname,
'req-url-params': JSON.stringify(request.page.params),
'req-url-page': request.page.name || '',
'req-url-query': request.nextUrl.searchParams.get('foo') || '',
'req-url-locale': request.nextUrl.locale,
},
})
}
export default function Index() {
return <p className="title">Static route</p>
}
import { NextMiddleware, NextResponse } from 'next/server'
export const middleware: NextMiddleware = async function (request) {
const url = request.nextUrl
if (url.searchParams.get('foo') === 'bar') {
url.pathname = '/redirects/new-home'
url.searchParams.delete('foo')
return Response.redirect(url)
}
if (url.pathname === '/redirects/old-home') {
url.pathname = '/redirects/new-home'
return NextResponse.redirect(url)
}
}
export default function Home() {
return (
<div>
<p className="title">Home Page</p>
</div>
)
}
export default function NewHome() {
return <p className="title">New Home</p>
}
export default function OldHome() {
return <p className="title">Old Home</p>
}
import { NextMiddleware, NextResponse } from 'next/server'
export const middleware: NextMiddleware = async function (request, ev) {
// eslint-disable-next-line no-undef
const { readable, writable } = new TransformStream()
const url = request.nextUrl
const writer = writable.getWriter()
const encoder = new TextEncoder()
const next = NextResponse.next()
// Header based on query param
if (url.searchParams.get('set-header') === 'true') {
next.headers.set('x-set-header', 'valid')
}
// Streams a basic response
if (url.pathname === '/responses/stream-a-response') {
ev.waitUntil(
(async () => {
writer.write(encoder.encode('this is a streamed '))
writer.write(encoder.encode('response'))
writer.close()
})()
)
return new Response(readable)
}
if (url.pathname === '/responses/bad-status') {
return new Response('Auth required', {
headers: { 'WWW-Authenticate': 'Basic realm="Secure Area"' },
status: 401,
})
}
// Sends response
if (url.pathname === '/responses/send-response') {
return new NextResponse(JSON.stringify({ message: 'hi!' }))
}
return next
}
export default function Home() {
return (
<div>
<p className="title">Hello Middleware</p>
</div>
)
}
import { NextMiddleware, NextResponse } from 'next/server'
export const middleware: NextMiddleware = async function (request) {
const url = request.nextUrl
if (url.pathname === '/') {
let bucket = request.cookies.bucket
if (!bucket) {
bucket = Math.random() >= 0.5 ? 'a' : 'b'
const response = NextResponse.rewrite(`/rewrites/${bucket}`)
response.cookie('bucket', bucket, { maxAge: 10000 })
return response
}
return NextResponse.rewrite(`/rewrites/${bucket}`)
}
return null
}
export default function Home() {
return <p className="title">Welcome Page A</p>
}
export default function Home() {
return <p className="title">Welcome Page B</p>
}
/* eslint-env jest */
import { join } from 'path'
import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '..')
describe('TypeScript Middleware', () => {
describe('next build', () => {
it('should not fail to build middleware', async () => {
const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).not.toMatch(/Failed to compile/)
expect(stderr).not.toMatch(/is not assignable to type/)
expect(code).toBe(0)
})
})
})
{
"compilerOptions": {
"esModuleInterop": true,
"module": "esnext",
"jsx": "preserve",
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true
},
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "pages"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment