I have a simple NextJS app where I have a client component that calls an API route.
I am trying to access some search params in a route that I created but it is always returning null.
My client component is like so which calls my API on click of a button
export default function ClientComponent() {
const getData = async ({
secretId
}) => {
const url = new URL('/api/mydata', window.location.href)
url.searchParams.set('secretId', secretId) // attaches the query param and this value is definitely there
const response = await fetch(url)
const data = await response.json()
console.log("data:", data)
}
return (
<button onClick={handleGetSecret}>
Reveal secret
</button>
)
}
I then have a route app/api/mydata/route.tsx which handles the request
import { NextRequest } from "next/server"
export async function GET(request: NextRequest) {
const secretId = request.nextUrl.searchParams.get('secretId')
console.log("secretId:", secretId)
return Response.json({ message: 'hello', secretId })
}
but somehow secretId
which I try get from the search params is always null.
I have tried converting this to a post endpoint to use the request body too but same thing happens. The value is always null
I have also tried calling this endpoint from Postman and the same thing happens. It seems NextJS isn’t able to access search params in route files even though I tried to follow this here
Any idea what might be causing the value to be returning null even when I can see the search param in my URL when I print the object?
NextURL {
[Symbol(NextURLInternal)]: {
url: URL {
href: 'http://localhost:3000/api/mydata?secretId=abc123',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/api/secrets',
search: '?secretId=abc123',
searchParams: URLSearchParams { 'secretId' => 'abc123' },
hash: ''
},
options: { headers: [Object], nextConfig: undefined },
basePath: '',
domainLocale: undefined,
defaultLocale: undefined,
buildId: undefined,
locale: undefined,
trailingSlash: false
}
}
You can see here a screenshot of my Postman request
and this is a cURL request I have tried
curl --location 'http://localhost:3000/api/mydata/?secretId=abc123'
2
Answers
Looks like it doesn't like mixed-case values such as
secretId
.However, when I convert it all to lowercase
secretid
, it works fineIf you’re sure that query parameter
secretId
is sent to your Next backend, please put this code inside<Your next-app root>/src/app/api/test-secret/route.ts
.Accessing
http://localhost:3000/api/test-secret?secretId=42
should now return42
. I have verified that this is working with [email protected].