protect dashboard route
Unanswered
Lesser Scaup posted this in #help-forum
Lesser ScaupOP
im using nextjs15 + authjs5
i have /,
/glossary,
/curate,
/curate/:id
i want to protect them i tried in page to put
but when i test. those routes without being logged and refresh for split second i can see the page then redirect
so im trying to move the check to midllware
i tried
and
but i can still access glossary, ( i don't want to have the if check inside the page)
can someone tell me what i'm doing wrong, the matcher is to include or exclude
i have /,
/glossary,
/curate,
/curate/:id
i want to protect them i tried in page to put
if(!session?.user) redirect('/auth)
but when i test. those routes without being logged and refresh for split second i can see the page then redirect
so im trying to move the check to midllware
i tried
import { auth } from './auth';
import { NextRequest, NextResponse } from 'next/server';
export async function middleware(req: NextRequest) {
const session = await auth();
if (!session?.user && req.nextUrl.pathname !== '/auth') {
const newUrl = new URL('/auth', req.nextUrl.origin);
return NextResponse.redirect(newUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
and
import { NextRequest, NextResponse } from 'next/server';
import { auth } from './auth';
// define the private routes
const privatePaths = ['/', '/glossary', '/curate'];
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// only check auth if path starts with a private path
if (privatePaths.some(path => pathname === path || pathname.startsWith(path + '/'))) {
const session = await auth();
if (!session?.user) {
const url = req.nextUrl.clone();
url.pathname = '/auth';
return NextResponse.redirect(url);
}
}
// everything else passes
return NextResponse.next();
}
export const config = {
matcher: ['/', '/glossary', '/curate/:path*'], // only these routes go through middleware
};
but i can still access glossary, ( i don't want to have the if check inside the page)
can someone tell me what i'm doing wrong, the matcher is to include or exclude
2 Replies
Newfoundland
Matcher is used to run the middleware only on the routes you specify. So it will run if the route you are on "matches" witht he ones in the matcher.
Lesser ScaupOP
the middleware and matcher were correct i just placed it inside src, even thou in docs they're saying at root level
but now in production it wont logout
but now in production it wont logout