How to Redirect If Unauthenticated in NextAuth v4 Using Middleware


How can we require users to login when unauthenticated while using NextAuth.js?

Global authentication checks in Next Auth can be quite simple using higher order components.

However, we can use Next.js 12 middleware to simplify this process further.

The code snippets in this article require NextAuth.js v4. Check out how to upgrade to version 4.

Suppose we have a protected /dashboard page that requires authentication.

If unauthenticated when accessing this page, users should be redirected to a login page, otherwise, it should show some dashboard for that user.

Let’s create a _middleware.jsx file in our /pages directory.

1. Redirect if unauthenticated using sessions

In our middleware, we can check if the path name is a protected page.

If the page being accessed is protected, we will fetch the session and verify that it exists.

If the user is unauthenticated, they will be redirected to /api/auth/signin.

If the user is authenticated or the page doesn’t require authentication, they will end up at NextResponse.next(), which doesn’t require any redirection.

import { getSession } from "next-auth/react";
import { NextResponse } from "next/server";
export async function middleware(req) {
  if (req.nextUrl.pathname === "/dashboard") {
    const session = await getSession({ req });
    if (!session) return NextResponse.redirect("/api/auth/signin");
  }
  return NextResponse.next();
}

2. Redirect if unauthenticated using tokens

Similarly, we can use JWTs to perform the same check.

import { getToken } from "next-auth/jwt";
import { NextResponse } from "next/server";
export async function middleware(req) {
  if (req.nextUrl.pathname === "/dashboard") {
    const session = await getToken({ req, secret: process.env.SECRET });
    if (!session) return NextResponse.redirect("/api/auth/signin");
  }
  return NextResponse.next();
}