Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useSearchParam() sometimes doesn't get param when set in NextResponse.redirect() #2616

Open
yoonthegoon opened this issue Jan 2, 2025 · 0 comments

Comments

@yoonthegoon
Copy link

What is the current behavior?

useSearchParam('redirect') from react-use returns null when redirected via next.js middleware after a router.push() navigation, despite the redirect parameter being present in the URL.

Steps to reproduce it and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have extra dependencies other than react-use. Paste the link to your JSFiddle or CodeSandbox example below:

  1. Set up a Next.js application with protected routes and authentication middleware.
  2. Create a form submission handler that uses router.push to navigate to a protected route:
  const params = new URLSearchParams()
  params.append('value', value.trim())
  router.push(`/protected?${params.toString()}`)
  1. Implement middleware that redirects to login for protected routes:
  // src/middleware.ts

  if (isProtectedPath && !accessToken) {
    const loginUrl = new URL('/auth/login', request.url)
    // Add the current path as a redirect parameter
    loginUrl.searchParams.set('redirect', `${request.nextUrl.pathname}?${request.nextUrl.searchParams}`)
    return NextResponse.redirect(loginUrl)
  }
  1. On the login page, attempt to access the redirect parameter using useSearchParam and observer that useSearchParam('redirect') returns null.

Note that this does not happen when pasting the URL directly into the address bar or clicking an anchor tag.

What is the expected behavior?

useSearchParam('redirect') should return the redirect parameter value from the URL, as useSearchParams.get('redirect') from next/navigation does.

A little about versions:

  • macOS 15.2 24C101 arm64
  • Google Chrome Version 133.0.6905.0 (Official Build) dev (arm64)
  • react 18.3.1
  • react-use 17.5.1

Did this worked in the previous package version?

🤷


I spent some time wondering why my redirect from my login page wasn't working and ended up testing with next/navigation for sanity and found I was sane.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant