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

Adds new userAgent docs to the next/server docs page #37613

Merged
merged 8 commits into from
Jun 22, 2022
23 changes: 22 additions & 1 deletion docs/api-reference/next/server.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ The `NextRequest` object is an extension of the native [`Request`](https://devel
- `cookies` - A [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) with cookies from the `Request`
- `nextUrl` - Includes an extended, parsed, URL object that gives you access to Next.js specific properties such as `pathname`, `basePath`, `trailingSlash` and `i18n`
- `ip` - Has the IP address of the `Request`
- `ua` - Has the user agent
- `geo` - (Optional) Has the geo location from the `Request`, provided by your hosting platform

You can use the `NextRequest` object as a direct replacement for the native `Request` interface, giving you more control over how you manipulate the request.
Expand Down Expand Up @@ -148,6 +147,28 @@ export function middleware(req: NextRequest) {
}
```

## userAgent

The `userAgent` helper allows you to interact with the user agent object from the request. It is abstracted from the native `Request` object, and is an opt in feature.

`userAgent` is fully typed and can be imported from `next/server`.
molebox marked this conversation as resolved.
Show resolved Hide resolved

```ts
molebox marked this conversation as resolved.
Show resolved Hide resolved
import { userAgent } from 'next/server'
```

```typescript
import { NextRequest, NextResponse, userAgent } from 'next/server'

export function middleware(request: NextRequest) {
const url = request.nextUrl
const { device } = userAgent(request)
const viewport = device.type === 'mobile' ? 'mobile' : 'desktop'
url.searchParams.set('viewport', viewport)
return NextResponse.rewrites(url)
}
```

### Why does redirect use 307 and 308?

When using `redirect()` you may notice that the status codes used are `307` for a temporary redirect, and `308` for a permanent redirect. While traditionally a `302` was used for a temporary redirect, and a `301` for a permanent redirect, many browsers changed the request method of the redirect, from a `POST` to `GET` request when using a `302`, regardless of the origins request method.
Expand Down