Next.js Discord

Discord Forum

Protect Pages in Next.js

Unanswered
Hamodi posted this in #help-forum
Open in Discord
I want to protect the signup page after the user is authenticated using middleware:
import { withAuth } from "next-auth/middleware"
import { NextResponse } from "next/server"

export default withAuth(
    function middleware(req) {
        if (req.nextUrl.pathname.startsWith("/dashboard")
            && req.nextauth.token?.role !== "ADMIN") {
              const url = req.nextUrl.clone();
              url.pathname = "/booking";
              return NextResponse.redirect(url);
        }

        if (req.nextUrl.pathname.startsWith("/booking")
            && req.nextauth.token?.role !== "USER") {
              const url = req.nextUrl.clone();
              url.pathname = "/dashboard";
              return NextResponse.redirect(url);
        }

        if (req.nextUrl.pathname.startsWith("/signup")
            && req.nextauth.token?.role !== "ADMIN") {
              const url = req.nextUrl.clone();
              url.pathname = "/booking";
              return NextResponse.redirect(url);
        } 

        if (req.nextUrl.pathname.startsWith("/signup")
            && req.nextauth.token?.role !== "USER") {
              const url = req.nextUrl.clone();
              url.pathname = "/dashboard";
              return NextResponse.redirect(url);
       } 
    },
    {
        callbacks: {
            authorized: ({ token }) => !!token
        },
    }
)

export const config = {
    matcher: ["/signup", "/dashboard/:path*", "/booking/:path*", "/settings/:path*"]
  };

0 Replies