Next.js Discord

Discord Forum

How to Handle Public and Protected Routes with Next-Auth Using Matchers

Unanswered
Wuchang bream posted this in #help-forum
Open in Discord
Wuchang breamOP
I need a public route and all other routes should be authenticated or protected.

PUBLIC: /organizations/create
PROTECTED: /organizations/*


import { withAuth } from "next-auth/middleware"
import { NextResponse } from "next/server"

export default withAuth(
  function middleware(req) {
    if (!req.nextauth.token) {
      return NextResponse.redirect(new URL("/auth/login", req.url))
    }
    return NextResponse.next()
  },
  {
    pages: { signIn: "/auth/login" },
  },
)

export const config = {
  matcher: ["/dashboard/:path*", "/organizations/:path*"],
}

11 Replies

you can ask gpt to generate a regex that matches /organizations/* but does not match /organizations/create
^\/organizations\/(?!create$)[^/]+$
Wuchang breamOP
this way?
export const config = {
  matcher: ["/dashboard/:path*", "^/organizations/(?!create$)[^/]+$"],
}
but it's not working
@Yi Lon Ma you can ask gpt to generate a regex that matches `/organizations/*` but does not match `/organizations/create`
Wuchang breamOP
@Wuchang bream this way? ts export const config = { matcher: ["/dashboard/:path*", "^/organizations/(?!create$)[^/]+$"], }
export const config = {
matcher: [
"/organizations/(?!create$).*",
],
};
@Yi Lon Ma export const config = { matcher: [ "/organizations/(?!create$).*", ], };
Wuchang breamOP
same error nextjs 15 and next-auth
@Wuchang bream same error nextjs 15 and next-auth
guess this won't work.

setup the matcher for every subroute and then check manually
Wuchang breamOP
but how?
Wuchang breamOP
Thank you for your time now it's work

"/organizations/((?!create).*)"