Next.js Discord

Discord Forum

Middleware Infinite Redirect in Production

Unanswered
DirtyCajunRice | AppDir posted this in #help-forum
Open in Discord
i add search params if they are not there when going to /activity. In development it works perfectly, but in production it causes a redirect loop. Any ideas why?

const middleware = (request: NextRequest) => {
  const url = new URL(request.url);
  const response = NextResponse.next();
  const defaults = {
    theme: 'blue',
    approval: 'unlimited',
    account: btoa(JSON.stringify({
      address: AddressZero,
      premium: process.env.NODE_ENV === 'development',
      loggedIn: false,
      chainId: 1,
    })),
    'local-tokens': JSON.stringify([]),
  }
  Object.entries(defaults).forEach(([key, value]) => {
    if (!request.cookies.get(`ts-${key}`)?.value) {
      response.cookies.set({
        name: `ts-${key}`,
        value,
        maxAge: 60 * 60 * 24 * 365 * 10,
        httpOnly: true,
      })
    }
  })
  if (url.pathname.startsWith('/activity')) {
    if (!url.searchParams.has('search') || !url.searchParams.has('filtered')) {
      const newUrl = new URL(url);
      if (!url.searchParams.has('search')) {
        newUrl.searchParams.set("search", "");
      }
      if (!url.searchParams.has('filtered')) {
        newUrl.searchParams.set("filtered", "")
      }
      return NextResponse.redirect(newUrl)
    }
  }
  return response;
}

38 Replies

bump - ive narrowed it down to search params… it really does not like redirecting to search params… im not sure why
this seems... very insecure
@Marchy this seems... very insecure
what is very insecure?
there's a cookie for just "logged in"?
theres nothing insecure about setting default cookies and adding some always used search params
@Marchy there's a cookie for just "logged in"?
thats a hydration helper for a client library. doesnt do anything with actual auth haha
@DirtyCajunRice | AppDir thats a hydration helper for a client library. doesnt do anything with actual auth haha
You say that.. but microsoft did that with hotmail in like 2012 😅
@Marchy You say that.. but microsoft did that with hotmail in like 2012 😅
i am sure 😂. its just to let the page know that the user has a crypto wallet connected so it waits to render stuff that needs window access if its not dummy data.
any ideas on the redirect?
  if (url.pathname.startsWith('/activity')) {
    if (!url.searchParams.has('search') || !url.searchParams.has('filtered')) {
      const newUrl = new URL(url);
      if (!url.searchParams.has('search')) {
        newUrl.searchParams.set("search", "");
      }
      if (!url.searchParams.has('filtered')) {
        newUrl.searchParams.set("filtered", "")
      }
      return NextResponse.redirect(newUrl)
    }
  }

This can probably be moved to rewrites
Do the cookies get set?
might also be an async issue
@Marchy Do the cookies get set?
yeah cookies work perfectly. its ONLY the search param redirect that causes the too many redirects
@DirtyCajunRice | AppDir yeah cookies work perfectly. its ONLY the search param redirect that causes the too many redirects
That actually kinda makes sense. Middleware runs on every request, and where you are redirecting to is also a new request
so, âž¿
yeah but the new request shouldnt fire
rewrites are what you need
@DirtyCajunRice | AppDir yeah but the new request shouldnt fire
it does, because you are redirecting (which is a new request)
but i am checking explicitly to see if the search params exist and only adding if they dont
so the new request should be new with the param and not fire the if check… no?
Middleware runs on all matching paths, by redirecting instead of rewriting, you are always redirecting
@Marchy Middleware runs on all matching paths, by redirecting instead of rewriting, you are always redirecting
im only redirecting if it matches the condition. it doesnt redirect if it doesnt match the search params. look at the bottom of the code block.
its a normal NextResponse.next()
This is your current logic
no its not
your yes and no are flipped, and your no that should be a yes isnt absolute
its conditional.
oh right, but yes that is the exact logic you are using
 if (url.pathname.startsWith('/activity')) {

.. adds search params
return NextResponse.redirect(newUrl) // /activity?search=''
@DirtyCajunRice | AppDir there is another conditional
Not in the code you provided?
@Marchy Not in the code you provided?
yes there is haha
 if (url.pathname.startsWith('/activity')) {
    if (!url.searchParams.has('search') || !url.searchParams.has('filtered')) {
its nested
if the path starts with activity, AND the search params dont have either of those search params, THEN add and redirect
its just nested for readability because of the long dot notation
if all of those conditions arent met, it doesnt redirect
@Marchy This is your current logic