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

Add TS types for NextMiddleware #30578

Merged
merged 22 commits into from
Nov 30, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
9 changes: 4 additions & 5 deletions docs/api-reference/next/server.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,11 @@ These native Web API objects are extended to give you more control over how you
The function signature:

```ts
import type { NextRequest, NextFetchEvent } from 'next/server'
import { NextMiddleware } from 'next/server'

export type Middleware = (
request: NextRequest,
event: NextFetchEvent
) => Promise<Response | undefined> | Response | undefined
export const middleware: NextMiddleware = function (request, event) {
return new Response('Hello world')
}
lfades marked this conversation as resolved.
Show resolved Hide resolved
styfle marked this conversation as resolved.
Show resolved Hide resolved
```

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.
Expand Down
1 change: 1 addition & 0 deletions packages/next/server.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { NextFetchEvent } from 'next/dist/server/web/spec-extension/fetch-event'
export { NextRequest } from 'next/dist/server/web/spec-extension/request'
export { NextResponse } from 'next/dist/server/web/spec-extension/response'
export { NextMiddleware } from 'next/server/web/types'
4 changes: 2 additions & 2 deletions packages/next/server/web/adapter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { RequestData, FetchEventResult } from './types'
import type { NextMiddleware, RequestData, FetchEventResult } from './types'
import { DeprecationError } from './error'
import { fromNodeHeaders } from './utils'
import { NextFetchEvent } from './spec-extension/fetch-event'
Expand All @@ -7,7 +7,7 @@ import { NextResponse } from './spec-extension/response'
import { waitUntilSymbol } from './spec-compliant/fetch-event'

export async function adapter(params: {
handler: (request: NextRequest, event: NextFetchEvent) => Promise<Response>
handler: NextMiddleware
page: string
request: RequestData
}): Promise<FetchEventResult> {
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/web/spec-extension/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export class NextResponse extends Response {
return this.cookie(name, '', { expires: new Date(1), path: '/', ...opts })
}

static redirect(url: string | NextURL, status = 302) {
static redirect(url: string | NextURL | URL, status = 302) {
if (!REDIRECTS.has(status)) {
throw new RangeError(
'Failed to execute "redirect" on "response": Invalid status code'
Expand Down
10 changes: 10 additions & 0 deletions packages/next/server/web/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
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 {
[header: string]: string | string[] | undefined
Expand Down Expand Up @@ -29,3 +32,10 @@ export interface FetchEventResult {
response: Response
waitUntil: Promise<any>
}

type NextMiddlewareResult = NextResponse | Response | null

export type NextMiddleware = (
request: NextRequest,
event: NextFetchEvent
) => NextMiddlewareResult | Promise<NextMiddlewareResult>
6 changes: 6 additions & 0 deletions test/integration/middleware-typescript/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
i18n: {
locales: ['en', 'fr', 'nl'],
defaultLocale: 'en',
},
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Index() {
return <p className="title">Dynamic route</p>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
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,
},
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Index() {
return <p className="title">Static route</p>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
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)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function Home() {
return (
<div>
<p className="title">Home Page</p>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function NewHome() {
return <p className="title">New Home</p>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function OldHome() {
return <p className="title">Old Home</p>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
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
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import Link from 'next/link'

export default function Home({ message }) {
return (
<div>
<p className="title">Hello Middleware</p>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
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
}
3 changes: 3 additions & 0 deletions test/integration/middleware-typescript/pages/rewrites/a.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Home() {
return <p className="title">Welcome Page A</p>
}
3 changes: 3 additions & 0 deletions test/integration/middleware-typescript/pages/rewrites/b.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Home() {
return <p className="title">Welcome Page B</p>
}
16 changes: 16 additions & 0 deletions test/integration/middleware-typescript/test/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/* 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)
})
})
})