Search code examples
next.jsnext-auth

restrict sign and signup page after auth nextauth nextjs


I'm trying to restrict sign and signup page after auth in nextauth nextjs through the given middleware:

import { getToken } from "next-auth/jwt";
import { NextResponse } from "next/server";

export async function middleware(req) {
  const url = req.nextUrl.clone();
  url.pathname = "/auth/new-user";
  if (req.nextUrl.pathname === "/" || req.nextUrl.pathname === "/settings") {
    const session = await getToken({
      req,
      secret: process.env.JWT_SECRET,
      secureCookie: process.env.NODE_ENV === "production",
    });
    // You could also check for any property on the session object,
    // like role === "admin" or name === "John Doe", etc.
    if (!session) return NextResponse.redirect(url);
    // If user is authenticated, continue.
  }
}

where it restricts the path '/' if the user is not auth which works great. but after auth the user is able to go back and see the sign in and sign up pages...

I was thinking of doing something like

    if (!session){
      return NextResponse.redirect(url);
    }else{
      return NextResponse.redirect('/')
    }

This still doesn't account for the other pages that need to be accounted for after the user is authenticated..


Solution

  • restrict make 2 different portions to differentiate between auth and after auth

    export async function middleware(req) {
      const auth = req.nextUrl.clone();
      auth.pathname = "/auth/new-user";
      const afterAuth = req.nextUrl.clone();
      afterAuth.pathname = "/";
    
      if (req.nextUrl.pathname === "/" || req.nextUrl.pathname === "/settings") {
        const session = await getToken({
          req,
          secret: process.env.JWT_SECRET,
          secureCookie: process.env.NODE_ENV === "production",
        });
        // You could also check for any property on the session object,
        // like role === "admin" or name === "John Doe", etc.
        if (!session) return NextResponse.redirect(auth);
        // If user is authenticated, continue.
      }
    
      if (req.nextUrl.pathname === "/auth/new-user" || req.nextUrl.pathname === "/auth/signin") {
        const session = await getToken({
          req,
          secret: process.env.JWT_SECRET,
          secureCookie: process.env.NODE_ENV === "production",
        });
        // You could also check for any property on the session object,
        // like role === "admin" or name === "John Doe", etc.
        if (session) return NextResponse.redirect(afterAuth);
        // If user is authenticated, continue.
      }
    }