Next.js Discord

Discord Forum

Middleware Redirect not working as expected

Unanswered
European sprat posted this in #help-forum
Open in Discord
Avatar
European spratOP
   if (!request.url.includes("/login")) { 
      return NextResponse.redirect(new URL("/", request.nextUrl));
   } 
  //what if im alreay on "/" this route why nextjs doesnot perfom full page redirect/reload if im already on the same route ? It just keeps on showing the loading progress bar and never reloads the page any insight would be helpful

47 Replies

Avatar
Barbary Lion
from you: "The only reason i had put it this way is because these routes are protected so when session expires and somebody visits those protected routes im trying to make redirect to "/" But when im already at "/" This route and try to access a protected route but for no reason my session expired and try accessing that route it just keeps loading and never refreshes"
@European sprat try asking phind.com and see if that gives you an alternative
thats the best I got
Avatar
European spratOP
Am i the only one facing such issues no one ever had such issues damm
Avatar
Northeast Congo Lion
nope! Got it too
basically my understanding is something with middleware and getServersideProps isn't working
This appears to be a widespread problem
Avatar
Asian black bear
What happens if you specifically create a 307 response instead of using the helper?
Avatar
European spratOP
When will it be solved its really im just trying to figure it out in every possible re posting every where no one giving me any response its depressing
Avatar
Northeast Congo Lion
is this you?
lol
I have no idea when it'll be solved
Avatar
European spratOP
No 😂😂
i guess down grading it might fix?
but then again which version made it broke
Avatar
Northeast Congo Lion
see if downgrading to 13.3.1 works
Does this happen on your development server or only prod?
Avatar
Northeast Congo Lion
@European sprat
Avatar
European spratOP
dev server @Northeast Congo Lion
not sure in production let me see
Avatar
Northeast Congo Lion
dang
Diff issue than what I was having then
Avatar
European spratOP
will see let me build and run prod server
same issue even in prod server the progress bar keeps loading never refreshes the page @Northeast Congo Lion
Avatar
Northeast Congo Lion
Can you remind me in about 12 hours to copy and paste the code I use for middleware redirects?
Avatar
European spratOP
which code you've used i didn't see any of your code or I missunderstood @Northeast Congo Lion
Avatar
Northeast Congo Lion
You misunderstood lol. I was going to sleep so I didnt have access to my code to give you. I asked you to remind me in 12 hours when I was awake and could give it to you lol
Doesnt really matter, when I'm fully up I'll see how I did middleware redirects and double check your work
Avatar
Northeast Congo Lion
Ok the number 1 thing I'm seeing here is that if you have any assets, static or otherwise, they're all going to redirect when you hit go somewhere other than /login
including /
so you're going to /
that isn't /login
so it's redirecting you to /
Avatar
Northeast Congo Lion
  if (login_exempt_urls.matching.includes(request.nextUrl.pathname)){
        //if the path is in the list of ignorable URLs, do not do the middleware process
        return NextResponse.next()
    }else{
        //if the url contains a part of the "contains" urls, skip it. 
        //this is for static assets such as css and js
        let skipThis = false
        login_exempt_urls.contains.forEach((url)=>{
            if (request.nextUrl.pathname.includes(url)){
                skipThis = true
            }
        })

        if (skipThis){
            return NextResponse.next()
        }
    }
    //validate the user's cookie
    const result = await verifyAuth(request)
    //if we don't skip this URL and the cookies are invalid, redirect.
    if (!result){
        return NextResponse.redirect(new URL('/login', request.url))
    }
This is what the equivalent middleware does on my system
for context:
const login_exempt_urls = {
    matching:["/",
        "",
        "/login",
        "/api/login",
        "/register",
        "/api/register",
        "/pwreset",
        "/api/resetPassword",
        "/api/finalResetStep"
    ],
    contains:[
        '_next/static/',
        "/resetPassword",
        "/portfolio/",
        "/verify"
    ]
}
Avatar
European spratOP
Will try to implement thanks
Avatar
Northeast Congo Lion
Yeah I can be 99% certain at this point the problem you're having is that your nextjs is trying to redirect you to an address you've explicitly marked is not acceptable for redirects. If you want it to work, you need to allow multiple addresses to be allowed without redirecting.
Avatar
European spratOP
There is also one more thing that if im on a different route lets say about page and try to access restricted route which requires auth/session in that case if i don't have the correct credentials it redirects me to "/" Page which is expected as soon as im already in "/" and try access a restricted route problem starts
Avatar
Northeast Congo Lion
I don't understand
Avatar
European spratOP
I mean to say is that im on page "/about"
Now i trying to access a restricted route "/admin" And my credentials got expired so it does redirects me to "/" Which is working perfectly fine in this case

But when im at "/" And try accessing "/admin" Also my credentials expired it tries to redirect me to "/" But it keeps showing progrees bar never reloads/redirect

As of now im thinking to make another page called "session expired" Which i will redirect this wont be accessible if you are logged in and if you are not logged in you must have a key "once_logged" Set to true
Avatar
Northeast Congo Lion
Well, from the code you showed us at the top of the post, if the url isn't literally "Login" you're going to get a redirect
which indicates you're either not showing all the relevant code, or literally login is the only page you can see without logging in, which it shouldn't be the case.
Avatar
European spratOP
import { NextResponse } from "next/server";
import * as jose from "jose";
const JWT_SECRET = "7hhs8992hhs7h7hs8hdb772b10**7$#";
// This function can be marked `async` if using `await` inside
export async function middleware(request) {
  const token = request.cookies.get("token")?.value || "";
  const urlPath = new URL(request.url).pathname;
  // console.log("urlpath", urlPath);

  try {
    const secret = new TextEncoder().encode(JWT_SECRET);
    const { payload } = await jose.jwtVerify(token, secret);
    //user is really an admin

    if (request.url.includes("/login") && payload.role == "admin") {
      return NextResponse.redirect(new URL("/", request.nextUrl));
    }
  } catch (error) {
    console.log("middleware_error", error);

    if (urlPath == "") return;
    if (request.url.includes("/api/")) {
      return NextResponse.json({
        message: "You are not authorized to access this",
      });
    }
    if (!request.url.includes("/login")) {
      console.log("ran");
      return NextResponse.redirect(new URL("/", request.nextUrl));
    }
  }
}

// See "Matching Paths" below to learn more
export const config = {
  matcher: [
    "/post/add",
    "/contributor/add",
    "/api/admin/post",
    "/api/admin/post/:id*",
    "/login",
  ],
};

Here you go little messay i was trying to figure out things