最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

next.js - How to assign search params to current url in middleware if not authorized? - Stack Overflow

programmeradmin0浏览0评论

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"
  ],
};

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"
  ],
};

Share Improve this question asked Mar 19 at 7:33 FreeFree 431 silver badge5 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 1

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)
}

new URL("/?modal=auth", req.url)

A relative URL that starts with a leading slash, refers to the domain root. If you want to overwrite the query string, but keep the current path, you need to use ?modal=auth instead.

发布评论

评论列表(0)

  1. 暂无评论