Skip to content

Commit

Permalink
Fix formData code snippet in route handler docs (#52532)
Browse files Browse the repository at this point in the history
### Why?

The code snippet in the Route handler `formData` documentation

```ts
import { NextResponse } from 'next/server'
 
export async function POST(request: Request) {
  const formData = await request.formData()
  return NextResponse.json({ formData })
}
```

is slightly wrong, because `formData` is not a plain object and hence `return NextResponse.json({ formData })` doesn't actually work.

Since we are already in the topic of parsing `formData`, I also added a mention on `zod-form-data` which can be used to validate the form and parse it to non-string formats such as `number`.
  • Loading branch information
joulev committed Jul 22, 2023
1 parent 7843204 commit a0ea5f2
Showing 1 changed file with 8 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,9 @@ import { NextResponse } from 'next/server'

export async function POST(request: Request) {
const formData = await request.formData()
return NextResponse.json({ formData })
const name = formData.get('name')
const email = formData.get('email')
return NextResponse.json({ name, email })
}
```

Expand All @@ -562,10 +564,14 @@ import { NextResponse } from 'next/server'

export async function POST(request) {
const formData = await request.formData()
return NextResponse.json({ formData })
const name = formData.get('name')
const email = formData.get('email')
return NextResponse.json({ name, email })
}
```

Since `formData` data are all strings, you may want to use [`zod-form-data`](https://www.npmjs.com/zod-form-data) to validate the request and retrieve data in the format you prefer (e.g. `number`).

### CORS

You can set CORS headers on a `Response` using the standard Web API methods:
Expand Down

0 comments on commit a0ea5f2

Please sign in to comment.