#Next middleware issue
1 messages · Page 1 of 1 (latest)
Hi @karmic matrix. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
You can use a negative lookahead in the matcher configuration to match everything except a specific path. In your case, you want to exclude the /auth page. Here's an example from the extracted information:
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
};
To adapt this example for your use case, you can modify the regex pattern to exclude the /auth path:
export const config = {
matcher: '/((?!auth).*)',
};
This configuration will match all paths except /auth. Make sure to use a constant value for the matcher, as dynamic values such as variables will be ignored.
Source: Next.js Middleware - Matching Paths (https://nextjs.org/docs/pages/building-your-application/routing/middleware#matching-paths)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@karmic matrix kapa.ai is still learning and improving, please let us how it did by reacting below
Thanks that works
@stuck ginkgo Do you know why when I use this code for my middleware and the token cookie is not set, it just displays a blank screen and not the auth page properly?
import { NextRequest, NextResponse } from "next/server";
import { verifyAuth } from "./lib/auth";
const redirectToAuth = (requestUrl: string) =>
NextResponse.redirect(new URL("/auth", requestUrl));
// This middleware function is used for guarding routes (auth).
export function middleware(request: NextRequest) {
const token = request.cookies.get("token");
if (!token) return redirectToAuth(request.url);
const isValid = verifyAuth(token.value);
if (!isValid) {
const response = redirectToAuth(request.url);
response.cookies.delete("token");
return response;
}
}
export const config = {
// prettier-ignore
matcher: "/((?!auth).*)",
};
Let me check the knowledge base for you. One moment! :books:
Based on the provided code and the information extracts, it's not clear why you're experiencing a blank screen instead of being redirected to the /auth page. However, I can provide some suggestions to help you debug the issue:
-
Make sure the
/authpage exists and is rendering correctly. You can test this by visiting the/authpage directly in your browser. -
Ensure that the
verifyAuthfunction in./lib/authis implemented correctly and returnstrueorfalsebased on the token's validity. -
If the issue persists, you can try adding some
console.logstatements in your middleware function to check the values oftoken,isValid, and the response object at different stages. This can help you identify where the problem might be occurring.