Protecting pages in app router with next-auth
Unanswered
American black bear posted this in #help-forum
American black bearOP
I want to protect pages in my nextjs 14 app.
Currently what I am doing is, I get the session with getServerSession hook and then check if the session is empty or not.
If the session is empty then I redirect to the login page.
I tried using middleware but for some reason it was not working properly. I was not able to even view the protected pages and was always redirected to the login page.
my middleware.ts file, I took reference from shadcn taxonomy repo
I don't know the best practice on how to protect pages, if someone can help me out. It would be great
Currently what I am doing is, I get the session with getServerSession hook and then check if the session is empty or not.
If the session is empty then I redirect to the login page.
export default async function DashboardPage() {
const session = await getServerSession(authOptions)
if (!session) {
return redirect("/?from=posts")
}
//...rest of componentI tried using middleware but for some reason it was not working properly. I was not able to even view the protected pages and was always redirected to the login page.
my middleware.ts file, I took reference from shadcn taxonomy repo
import { NextResponse } from "next/server"
import { getToken } from "next-auth/jwt"
import { withAuth } from "next-auth/middleware"
export default withAuth(
async function middleware(req) {
const token = await getToken({ req })
const isAuth = !!token
const isAuthPage = req.nextUrl.pathname === "/"
if (isAuthPage) {
if (isAuth) {
return NextResponse.redirect(new URL("/posts", req.url))
}
return null
}
if (!isAuth) {
let from = req.nextUrl.pathname
if (req.nextUrl.search) {
from += req.nextUrl.search
}
return NextResponse.redirect(
new URL(`/?from=${encodeURIComponent(from)}`, req.url)
)
}
},
{
callbacks: {
async authorized() {
// This is a work-around for handling redirect on auth pages.
// We return true here so that the middleware function above
// is always called.
return true
},
},
}
)
export const config = {
matcher: ["/", "/posts/:path*", "/comments"],
}I don't know the best practice on how to protect pages, if someone can help me out. It would be great
2 Replies
You can try grouping your page into groups and then do server-side validation in template.js
This way you can fine tune authorization process which middleware lack
https://nextjs.org/docs/getting-started/project-structure#route-groups-and-private-folders
https://nextjs.org/docs/app/api-reference/file-conventions/template
This way you can fine tune authorization process which middleware lack
https://nextjs.org/docs/getting-started/project-structure#route-groups-and-private-folders
https://nextjs.org/docs/app/api-reference/file-conventions/template
/home (public)/(admin)/template.ts (add your auth check here)/(admin)/**/page.ts (protected)