docs: Use Response.json over NextResponse.json (#56173)

TypeScript 5.2 now supports `Response.json` (https://github.com/microsoft/TypeScript/issues/52841). That means, if we just need to return a JSON `Response`, we no longer need to import `NextResponse`. This PR updates all such instances in the documentation to use `Response.json`.
This commit is contained in:
Vũ Văn Dũng 2023-09-29 02:36:21 +07:00 committed by GitHub
parent 141ccef608
commit 7f6a494e9e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 42 additions and 75 deletions

View file

@ -50,8 +50,6 @@ In addition to supporting native [Request](https://developer.mozilla.org/docs/We
Route Handlers are cached by default when using the `GET` method with the `Response` object.
```ts filename="app/items/route.ts" switcher
import { NextResponse } from 'next/server'
export async function GET() {
const res = await fetch('https://data.mongodb-api.com/...', {
headers: {
@ -61,13 +59,11 @@ export async function GET() {
})
const data = await res.json()
return NextResponse.json({ data })
return Response.json({ data })
}
```
```js filename="app/items/route.js" switcher
import { NextResponse } from 'next/server'
export async function GET() {
const res = await fetch('https://data.mongodb-api.com/...', {
headers: {
@ -77,11 +73,11 @@ export async function GET() {
})
const data = await res.json()
return NextResponse.json({ data })
return Response.json({ data })
}
```
> **TypeScript Warning:** Although `Response.json()` is valid, native TypeScript types currently shows an error, you can use [`NextResponse.json()`](/docs/app/api-reference/functions/next-response#json) for typed responses instead.
> **TypeScript Warning:** `Response.json()` is only valid from TypeScript 5.2. If you use a lower TypeScript version, you can use [`NextResponse.json()`](/docs/app/api-reference/functions/next-response#json) for typed responses instead.
### Opting out of caching
@ -95,8 +91,6 @@ You can opt out of caching by:
For example:
```ts filename="app/products/api/route.ts" switcher
import { NextResponse } from 'next/server'
export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
const id = searchParams.get('id')
@ -108,13 +102,11 @@ export async function GET(request: Request) {
})
const product = await res.json()
return NextResponse.json({ product })
return Response.json({ product })
}
```
```js filename="app/products/api/route.js" switcher
import { NextResponse } from 'next/server'
export async function GET(request) {
const { searchParams } = new URL(request.url)
const id = searchParams.get('id')
@ -126,15 +118,13 @@ export async function GET(request) {
})
const product = await res.json()
return NextResponse.json({ product })
return Response.json({ product })
}
```
Similarly, the `POST` method will cause the Route Handler to be evaluated dynamically.
```ts filename="app/items/route.ts" switcher
import { NextResponse } from 'next/server'
export async function POST() {
const res = await fetch('https://data.mongodb-api.com/...', {
method: 'POST',
@ -147,13 +137,11 @@ export async function POST() {
const data = await res.json()
return NextResponse.json(data)
return Response.json(data)
}
```
```js filename="app/items/route.js" switcher
import { NextResponse } from 'next/server'
export async function POST() {
const res = await fetch('https://data.mongodb-api.com/...', {
method: 'POST',
@ -166,7 +154,7 @@ export async function POST() {
const data = await res.json()
return NextResponse.json(data)
return Response.json(data)
}
```
@ -206,28 +194,24 @@ The following examples show how to combine Route Handlers with other Next.js API
You can [revalidate cached data](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) using the [`next.revalidate`](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) option:
```ts filename="app/items/route.ts" switcher
import { NextResponse } from 'next/server'
export async function GET() {
const res = await fetch('https://data.mongodb-api.com/...', {
next: { revalidate: 60 }, // Revalidate every 60 seconds
})
const data = await res.json()
return NextResponse.json(data)
return Response.json(data)
}
```
```js filename="app/items/route.js" switcher
import { NextResponse } from 'next/server'
export async function GET() {
const res = await fetch('https://data.mongodb-api.com/...', {
next: { revalidate: 60 }, // Revalidate every 60 seconds
})
const data = await res.json()
return NextResponse.json(data)
return Response.json(data)
}
```
@ -571,20 +555,16 @@ export async function GET() {
You can read the `Request` body using the standard Web API methods:
```ts filename="app/items/route.ts" switcher
import { NextResponse } from 'next/server'
export async function POST(request: Request) {
const res = await request.json()
return NextResponse.json({ res })
return Response.json({ res })
}
```
```js filename="app/items/route.js" switcher
import { NextResponse } from 'next/server'
export async function POST(request) {
const res = await request.json()
return NextResponse.json({ res })
return Response.json({ res })
}
```
@ -593,24 +573,20 @@ export async function POST(request) {
You can read the `FormData` using the `request.formData()` function:
```ts filename="app/items/route.ts" switcher
import { NextResponse } from 'next/server'
export async function POST(request: Request) {
const formData = await request.formData()
const name = formData.get('name')
const email = formData.get('email')
return NextResponse.json({ name, email })
return Response.json({ name, email })
}
```
```js filename="app/items/route.js" switcher
import { NextResponse } from 'next/server'
export async function POST(request) {
const formData = await request.formData()
const name = formData.get('name')
const email = formData.get('email')
return NextResponse.json({ name, email })
return Response.json({ name, email })
}
```

View file

@ -295,7 +295,7 @@ export function middleware(request) {
You can respond from Middleware directly by returning a `Response` or `NextResponse` instance. (This is available since [Next.js v13.1.0](https://nextjs.org/blog/next-13-1#nextjs-advanced-middleware))
```ts filename="middleware.ts" switcher
import { NextRequest, NextResponse } from 'next/server'
import { NextRequest } from 'next/server'
import { isAuthenticated } from '@lib/auth'
// Limit the middleware to paths starting with `/api/`
@ -307,16 +307,15 @@ export function middleware(request: NextRequest) {
// Call our authentication function to check the request
if (!isAuthenticated(request)) {
// Respond with JSON indicating an error message
return new NextResponse(
JSON.stringify({ success: false, message: 'authentication failed' }),
{ status: 401, headers: { 'content-type': 'application/json' } }
return Response.json(
{ success: false, message: 'authentication failed' },
{ status: 401 }
)
}
}
```
```js filename="middleware.js" switcher
import { NextResponse } from 'next/server'
import { isAuthenticated } from '@lib/auth'
// Limit the middleware to paths starting with `/api/`
@ -328,9 +327,9 @@ export function middleware(request) {
// Call our authentication function to check the request
if (!isAuthenticated(request)) {
// Respond with JSON indicating an error message
return new NextResponse(
JSON.stringify({ success: false, message: 'authentication failed' }),
{ status: 401, headers: { 'content-type': 'application/json' } }
return Response.json(
{ success: false, message: 'authentication failed' },
{ status: 401 }
)
}
}

View file

@ -149,7 +149,7 @@ https://<your-site.com>/api/revalidate?tag=collection&secret=<token>
```
```ts filename="app/api/revalidate/route.ts" switcher
import { NextRequest, NextResponse } from 'next/server'
import { NextRequest } from 'next/server'
import { revalidateTag } from 'next/cache'
// e.g a webhook to `your-website.com/api/revalidate?tag=collection&secret=<token>`
@ -158,21 +158,20 @@ export async function POST(request: NextRequest) {
const tag = request.nextUrl.searchParams.get('tag')
if (secret !== process.env.MY_SECRET_TOKEN) {
return NextResponse.json({ message: 'Invalid secret' }, { status: 401 })
return Response.json({ message: 'Invalid secret' }, { status: 401 })
}
if (!tag) {
return NextResponse.json({ message: 'Missing tag param' }, { status: 400 })
return Response.json({ message: 'Missing tag param' }, { status: 400 })
}
revalidateTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
return Response.json({ revalidated: true, now: Date.now() })
}
```
```js filename="app/api/revalidate/route.js" switcher
import { NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
// e.g a webhook to `your-website.com/api/revalidate?tag=collection&secret=<token>`
@ -181,52 +180,51 @@ export async function POST(request) {
const tag = request.nextUrl.searchParams.get('tag')
if (secret !== process.env.MY_SECRET_TOKEN) {
return NextResponse.json({ message: 'Invalid secret' }, { status: 401 })
return Response.json({ message: 'Invalid secret' }, { status: 401 })
}
if (!tag) {
return NextResponse.json({ message: 'Missing tag param' }, { status: 400 })
return Response.json({ message: 'Missing tag param' }, { status: 400 })
}
revalidateTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
return Response.json({ revalidated: true, now: Date.now() })
}
```
Alternatively, you can use [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) to revalidate all data associated with a path.
```ts filename="app/api/revalidate/route.ts" switcher
import { NextRequest, NextResponse } from 'next/server'
import { NextRequest } from 'next/server'
import { revalidatePath } from 'next/cache'
export async function POST(request: NextRequest) {
const path = request.nextUrl.searchParams.get('path')
if (!path) {
return NextResponse.json({ message: 'Missing path param' }, { status: 400 })
return Response.json({ message: 'Missing path param' }, { status: 400 })
}
revalidatePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
return Response.json({ revalidated: true, now: Date.now() })
}
```
```js filename="app/api/revalidate/route.js" switcher
import { NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
export async function POST(request) {
const path = request.nextUrl.searchParams.get('path')
if (!path) {
return NextResponse.json({ message: 'Missing path param' }, { status: 400 })
return Response.json({ message: 'Missing path param' }, { status: 400 })
}
revalidatePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
return Response.json({ revalidated: true, now: Date.now() })
}
```

View file

@ -240,18 +240,14 @@ export default function Page() {
Route Handlers will render a static response when running `next build`. Only the `GET` HTTP verb is supported. This can be used to generate static HTML, JSON, TXT, or other files from cached or uncached data. For example:
```ts filename="app/data.json/route.ts" switcher
import { NextResponse } from 'next/server'
export async function GET() {
return NextResponse.json({ name: 'Lee' })
return Response.json({ name: 'Lee' })
}
```
```js filename="app/data.json/route.js" switcher
import { NextResponse } from 'next/server'
export async function GET() {
return NextResponse.json({ name: 'Lee' })
return Response.json({ name: 'Lee' })
}
```

View file

@ -73,17 +73,17 @@ export default async function submit() {
```ts filename="app/api/revalidate/route.ts" switcher
import { revalidatePath } from 'next/cache'
import { NextRequest, NextResponse } from 'next/server'
import { NextRequest } from 'next/server'
export async function GET(request: NextRequest) {
const path = request.nextUrl.searchParams.get('path')
if (path) {
revalidatePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
return Response.json({ revalidated: true, now: Date.now() })
}
return NextResponse.json({
return Response.json({
revalidated: false,
now: Date.now(),
message: 'Missing path to revalidate',
@ -92,7 +92,6 @@ export async function GET(request: NextRequest) {
```
```js filename="app/api/revalidate/route.js" switcher
import { NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
export async function GET(request) {
@ -100,10 +99,10 @@ export async function GET(request) {
if (path) {
revalidatePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
return Response.json({ revalidated: true, now: Date.now() })
}
return NextResponse.json({
return Response.json({
revalidated: false,
now: Date.now(),
message: 'Missing path to revalidate',

View file

@ -46,23 +46,22 @@ export default async function submit() {
### Route Handler
```ts filename="app/api/revalidate/route.ts" switcher
import { NextRequest, NextResponse } from 'next/server'
import { NextRequest } from 'next/server'
import { revalidateTag } from 'next/cache'
export async function GET(request: NextRequest) {
const tag = request.nextUrl.searchParams.get('tag')
revalidateTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
return Response.json({ revalidated: true, now: Date.now() })
}
```
```js filename="app/api/revalidate/route.js" switcher
import { NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
export async function GET(request) {
const tag = request.nextUrl.searchParams.get('tag')
revalidateTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
return Response.json({ revalidated: true, now: Date.now() })
}
```