Redirect in Middleware in Next.js 14

Here's how to redirect in middleware in Next.js 14.

Redirect example

Here's a simple example of src/middleware.ts that does a redirect:

import { NextRequest, NextResponse } from 'next/server'

export default function middleware(req: NextRequest) {
  return requireLogin() ?? NextResponse.next()
}

function requireLogin() {
  if (!isLoggedIn()) {
    return NextResponse.redirect('/login')
  }
}

export const config = {
  matcher: ['/protected/:path*', '/other/:path*'],
}

Example explanation

There are some specifics to note to make sure we can get this right.

The request parameter in middleware is still the NextRequest type. This is odd in Next.js 14, because since 13 we've had the native Request type in API routes (ie route.ts files). That would have been nice here too. Then we could have used redirect() from "next/navigation".

The redirect return value must be returned from the middleware function. Without the return, it won't have an effect. If, in the case the redirect is not required, the NextResponse.next() value is returned.

The config export will specify which urls the middleware applies to. There are a couple example paths in the code snippet. This is not required. Without it, the middleware fires on all request paths.

To avoid confusion, I note that isLoggedIn is not implemented in the snippet and that it'd need implemented elsewhere.