Skip to content

Commit

Permalink
Add async to middleware docs. (vercel#31356)
Browse files Browse the repository at this point in the history
* Add `async` to middleware docs. 

I was reading the docs and got nervous. It looked like middleware didn't support async/await. After digging into the examples I found out it is possible. 

Not 100% sure if this is the docs change yahs want, but I thought I'd open a PR just incase.

* Add middleware API note

Co-authored-by: JJ Kasper <jj@jjsweb.site>
  • Loading branch information
2 people authored and natew committed Feb 16, 2022
1 parent 2937981 commit 035f7ac
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions docs/middleware.md
Expand Up @@ -30,6 +30,28 @@ export function middleware(req: NextRequest, ev: NextFetchEvent) {

In this example, we use the standard Web API Response ([MDN](https://developer.mozilla.org/en-US/docs/Web/API/Response)).

## API

Middleware is created by using a `middleware` function that lives inside a `_middleware` file. Its 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.

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:

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

export type Middleware = (
request: NextRequest,
event: NextFetchEvent
) => Promise<Response | undefined> | Response | undefined
```
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.
**Note:** Edge Functions are currently in Beta. The API might change as we look to continually make improvements.
## Examples
Middleware can be used for anything that shares logic for a set of pages, including:
Expand Down

0 comments on commit 035f7ac

Please sign in to comment.