How can I implement protected routes in Next.js with NextAuth? #82645
Unanswered
PatrickMeirelles
asked this question in
Help
Replies: 1 comment
-
For protecting routes with NextAuth.js in Next.js 14 App Router, use middleware:Create import { withAuth } from "next-auth/middleware"
export default withAuth({
callbacks: {
authorized: ({ token }) => !!token,
},
pages: {
signIn: "/login", // Custom login page (optional)
},
})
export const config = {
matcher: ["/dashboard/:path*"] // Add all protected routes here
}This approach:
Note: Without the More info: NextAuth.js Middleware Docs |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Hi everyone,
I'm using Next.js 14 with the App Router and NextAuth.js for authentication.
I want to restrict access to certain pages so that only logged-in users can view them, and redirect unauthenticated users to the login page.
Here's what I have so far:
jsx
// app/dashboard/page.jsx
export default function DashboardPage() {
return
Private Dashboard
;}
I have NextAuth set up, and the login works fine, but I'm not sure how to protect the /dashboard route.
What's the recommended way to do this in the App Router?
Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions