# next/server

The next/servermodule provides several exports for server-only helpers, such as Middleware .

# NextMiddleware

Middleware is created by using a middlewarefunction that lives inside a _middlewarefile. The Middleware API is based upon the native Request , FetchEvent , and Response 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 is defined as follows:

type NextMiddlewareResult = NextResponse | Response | null | undefined

type NextMiddleware = (
  request: NextRequest,
  event: NextFetchEvent
) => NextMiddlewareResult | Promise<NextMiddlewareResult>

It can be imported from next/serverwith the following:

import type { NextMiddleware } from 'next/server'

The function can be a default export and as such, does nothave to be named middleware. Though this is a convention. Also note that you only need to make the function asyncif you are running asynchronous code.

# NextRequest

The NextRequestobject is an extension of the native Request interface, with the following added methods and properties:

  • cookies- Has the cookies from the Request

  • nextUrl- Includes an extended, parsed, URL object that gives you access to Next.js specific properties such as pathname, basePath, trailingSlashand i18n

  • geo- Has the geo location from the Request

  • geo.country- The country code

  • geo.region- The region code

  • geo.city- The city

  • geo.latitude- The latitude

  • geo.longitude- The longitude

  • ip- Has the IP address of the Request

  • ua- Has the user agent

You can use the NextRequestobject as a direct replacement for the native Requestinterface, giving you more control over how you manipulate the request.

NextRequestis fully typed and can be imported from next/server.

import type { NextRequest } from 'next/server'

# NextFetchEvent

The NextFetchEventobject extends the native FetchEvent object, and includes the waitUntil() method.

The waitUntil()method can be used to prolong the execution of the function, after the response has been sent. In practice this means that you can send a response, then continue the function execution if you have other background work to make.

An example of whyyou would use waitUntil()is integrations with logging tools such as Sentry or DataDog . After the response has been sent, you can send logs of response times, errors, API call durations or overall performance metrics.

The eventobject is fully typed and can be imported from next/server.

import type { NextFetchEvent } from 'next/server'

# NextResponse

The NextResponseobject is an extension of the native Response interface, with the following added methods and properties:

  • cookies- An object with the cookies in the Response
  • cookie- Set a cookie in the Response
  • redirect()- Returns a NextResponsewith a redirect set
  • rewrite()- Returns a NextResponsewith a rewrite set
  • next()- Returns a NextResponsethat will continue the middleware chain

All methods above return a NextResponseobject that only takes effect if it's returned in the middleware function.

NextResponseis fully typed and can be imported from next/server.

import { NextResponse } from 'next/server'

# Why does redirect use 307 and 308?

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

Taking the following example of a redirect from /usersto /people, if you make a POSTrequest to /usersto create a new user, and are conforming to a 302temporary redirect, the request method will be changed from a POSTto a GETrequest. This doesn't make sense, as to create a new user, you should be making a POSTrequest to /people, and not a GETrequest.

The introduction of the 307status code means that the request method is preserved as POST.

  • 302- Temporary redirect, will change the request method from POSTto GET
  • 307- Temporary redirect, will preserve the request method as POST

The redirect()method uses a 307by default, instead of a 302temporary redirect, meaning your requests will alwaysbe preserved as POSTrequests.

# How do I access Environment Variables?

process.envcan be used to access Environment Variables from Middleware. These are evaluated at build time, so only environment variables actuallyused will be included.

Any variables in process.envmust be accessed directly, and cannotbe destructured:

// Accessed directly, and not destructured works. process.env.NODE_ENV is `"development"` or `"production"`
console.log(process.env.NODE_ENV)
// This will not work
const { NODE_ENV } = process.env
// NODE_ENV is `undefined`
console.log(NODE_ENV)
// process.env is `{}`
console.log(process.env)

Edge RuntimeLearn more about the supported Web APIs available. MiddlewareRun code before a request is completed.

Last Updated: 5/13/2023, 8:55:38 PM