Next.js Discord

Discord Forum

Why does my NextResponse.redirect() swallow the message param?

Unanswered
Egyptian Mau posted this in #help-forum
Open in Discord
Egyptian MauOP
I have this redirect in my middleware, however the message doesn't get sent along, is it because of the callbackUrl?

return NextResponse.redirect(
        new URL(
          isUser
            ? "/"
            : "/auth/signin?message=You are not authorized admin role needed!",
          req.url
        )
      );


Resulting url:

http://localhost:3000/auth/signin?callbackUrl=http%3A%2F%2Flocalhost%3A3000%2Fadmin

14 Replies

I guess thats just how Url works.
I think a better idea would be to just create a new UrlSearchParams object and create the params using it.
Egyptian MauOP
I will give it a try.
Cant use any hooks, I am in a middleware file.
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";

export default withAuth(
  function middleware(req) {
    const isUser = req.nextauth.token?.user?.role === "user";
    const isAdmin = req.nextauth.token?.user?.role === "admin";
    if (req.nextUrl.pathname.startsWith("/admin") && !isAdmin) {
      const url = new URL(isUser ? "/" : "/auth/signin", req.url);
      url.searchParams.append(
        "message",
        "You are not authorized admin role needed!"
      );
      return NextResponse.redirect(url);
    }
    if (req.nextUrl.pathname.startsWith("/user") && !isUser && !isAdmin) {
      const url = new URL(isUser ? "/" : "/auth/signin", req.url);
      url.searchParams.append(
        "message",
        "You are not authorized user or admin role needed!"
      );
      return NextResponse.redirect(url);
    }
  },
  {
    callbacks: {
      //true = user is authorized, false = not
      authorized: ({ token }) => !!token,
    },
  }
);

//Routes this middleware runs for.
export const config = {
  matcher: ["/user", "/admin/:path*"],
};
UrlSearchParams shouldn't need a hook
Egyptian MauOP
sorry I misunderstood what you meant, I tried it this way it doesnt work sadly.
I think the creation of the searchParams is not the issue they just disappear somehow.
You shouldn't be using Url at all
@Clown I guess thats just how `Url` works.
Thats probably what's making your params disappear. You can just pass a string to redirect
Egyptian MauOP
Just a string doesnt work either sadly.
As in? Send what you are doing currently
Egyptian MauOP
      return NextResponse.redirect("/auth/signin?message=test");