next.js

How to assign search params to current url in middleware if not authorized?


For example, if the user is on the page http://localhost/article/1

Assign ?modal=auth to the current URL

http://localhost/article/1?modal=auth

Here is my middleware. At the moment, if the user is not authorized, it redirects to /?modal=auth

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export async function middleware(req: NextRequest) {
  const token = req.cookies.get("session")?.value || "";
  const res = await fetch(`${process.env.HOST}/api/user/me`, {
    headers: {
      cookie: `session=${token}`,
    },
  });
  const user = await res.json();

  const { pathname } = req.nextUrl;

  if (!token || res.status === 403) {
    return NextResponse.redirect(new URL("/?modal=auth", req.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    "/my",
    "/bookmarks",
    "/new"
  ],
};


Solution

  • Right now you are precisely redirecting to /?modal=auth

    Create a concatenated URL instead:

    const url = request.nextUrl.clone();
    
    if (!token || res.status === 403) {
        return NextResponse.redirect(url.origin + "/?modal=auth");
      }
    

    Or you can use this method present in Next docs:

    
    if (!token || res.status === 403) {
    // Given an incoming request...
    const loginUrl = request.nextUrl.clone();
    
    loginUrl.searchParams.set('modal',"auth");
    
    // And redirect to the new URL
    return NextResponse.redirect(loginUrl)
    }