Next.js Discord

Discord Forum

Next.js middleware help needed

Unanswered
rand posted this in #help-forum
Open in Discord
Hi everyone.
I am going to add auth query automatically to url when router change.
I can see console log is working properly but not showing in frontend.
Here is my middleware
import { getToken } from "next-auth/jwt";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export async function middleware(req: NextRequest) {
  const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
  const { pathname } = req.nextUrl;
  const url = req.nextUrl.clone();

  url.searchParams.set("auth", token ? "true" : "false");
  console.log(url.href);
  if (pathname === "/" && token) {
    url.pathname = "/mockup";
    return NextResponse.redirect(url);
  }

  return NextResponse.rewrite(url);
}

export const config = {
  matcher: [
    // Match all routes except static files and APIs
    "/((?!api|_next/static|_next/image|favicon.ico).*)",
  ],
};

I have attached console log in vscode.

2 Replies

bump