Next.js Discord

Discord Forum

Help in Route.

Answered
Verin posted this in #help-forum
Open in Discord
Yo.
How can I redirect all requests to the signin page if not logged user try to access?
Answered by averydelusionalperson
If you're using next-auth, you can do it like this ig: https://next-auth.js.org/configuration/nextjs#middleware
View full answer

28 Replies

use middleware
@averydelusionalperson use middleware
I've done it and it's working well in the dev mode.
but when I build it, there is an error.
When I use the HOC, the main page rendered and then redirect to the login page. 😓
would you share the code of your middleware?
import { getSession } from 'next-auth/react'
import { NextResponse } from 'next/server'
// import type { NextRequest } from 'next/server'

// This function can be marked async if using await inside
export async function middleware(request) {
const requestForNextAuth = {
headers: {
cookie: request.headers.get('cookie'),
},
};

const session = await getSession({ req: requestForNextAuth });

if (session) {
return NextResponse.next()
} else {
return NextResponse.redirect(new URL('/auth/signin', request.url))
}

}

// See "Matching Paths" below to learn more
export const config = {
matcher: '/((?!auth|api|_next/static|_next/image|favicon.ico).*)'
}
I think you should update the matcher right or the entire application needs login?
since you won't be able to access even the logi page
I said it's working well in the dev mode but not work in building.
hmm
what's the error in the prod/build?
@averydelusionalperson what's the error in the prod/build?
login page route is auth/signin.
Let me show the error.
next build

â–² Next.js 14.1.3
- Environments: .env

Creating an optimized production build ...
Failed to compile.

./node_modules/@babel/runtime/regenerator/index.js
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation

Import trace for requested module:
./node_modules/@babel/runtime/regenerator/index.js
./node_modules/next-auth/react/index.js


Build failed because of webpack errors
If you're using next-auth, you can do it like this ig: https://next-auth.js.org/configuration/nextjs#middleware
Answer
Oh, that looks sweat.
yeah
let me try now.
@Verin Did it work?
yes,yes,
thanks
Original message was deleted
Your welcome, consider marking a message as solution
sure.
🫡
👍
I need your help for another things.
Please open a new post
@joulev Please open a new post
I've open a new post.