useSearchParams() is empty if from a middleware rewrite
Unanswered
Marble gall posted this in #help-forum
Marble gallOP
I have the middleware below
Below is the anime page, for some reason if we do a normal
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
// Get the pathname
const pathname = request.nextUrl.pathname;
// Check if the path matches /g/{genre}
const genreMatch = pathname.match(/^\/g\/([^\/]+)$/);
if (genreMatch) {
// Get the genre from the match
const genre = decodeURIComponent(genreMatch[1]);
// Create the new URL with the anime path and genre query parameter
const url = new URL('/anime', request.url);
url.searchParams.set('genre', encodeURIComponent(genre));
// console.log(url.toString());
// Return rewrite response
return NextResponse.rewrite(url);
}
// Continue with the request if no matches
return NextResponse.next();
}
Below is the anime page, for some reason if we do a normal
/anime?genre=SampleGenre
the genre
variable has a value but if we go to /g/SampleGenre
we get undefinedc#
'use client';
import { useSearchParams } from 'next/navigation';
import { useState } from 'react';
import { useAnimeDiscovery } from '@/lib/queries/animeQueries';
import MovieCard from '@/components/MovieCard';
import { Button } from '@/components/ui/button';
export const dynamic = 'force-dynamic';
export default function Movies() {
const searchParams = useSearchParams();
const [page, setPage] = useState(1);
const genre = searchParams.get('genre');
const search = searchParams.get('search');
const sort = searchParams.get('sort') || 'updatedAt';
const order = searchParams.get('order') || 'desc';
1 Reply
Hi!
The [doc](https://nextjs.org/docs/app/building-your-application/upgrading/from-create-react-app) here say:
Preserving mean that the browser doesn't update and only the server is called with the proxy value. Hooks are only used on the frontend side.
If you meant to edit the url for the frontend, you want to redirect so the hook can find the data.
But with a redirect, you will end up with
Since you are using a route with
The [doc](https://nextjs.org/docs/app/building-your-application/upgrading/from-create-react-app) here say:
Produce a response that rewrites (proxies) the given URL while preserving the original URL.
// Incoming request: /about, browser shows /about
// Rewritten request: /proxy, browser shows /about
return NextResponse.rewrite(new URL('/proxy', request.url))
Preserving mean that the browser doesn't update and only the server is called with the proxy value. Hooks are only used on the frontend side.
If you meant to edit the url for the frontend, you want to redirect so the hook can find the data.
But with a redirect, you will end up with
/g/SampleGenre?genre=SampleGenre
Since you are using a route with
/g/[genre]
you can probably get your variable from useParams
instead of useSearchParams