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

15 messages · Page 1 of 1 (latest)

boreal river
#

I have this redirect in my middleware, however the message doesn't get sent along, is it because of the callbackUrl?

        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```
untold latchBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

astral compass
#

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.

boreal river
#

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

astral compass
#

UrlSearchParams shouldn't need a hook

boreal river
#

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.

astral compass
#

You shouldn't be using Url at all

astral compass
boreal river
#

Just a string doesnt work either sadly.

astral compass
#

As in? Send what you are doing currently