Next.js Discord

Discord Forum

search params are returned as null eventhough its visible on console.log(request.nextURL) in server.

Unanswered
Wishwa posted this in #help-forum
Open in Discord
this is what i get as next version: Next.js v15.2.0-canary.16 --> App router

I am trying to access the query parameters sent by client side from nextjs internal API

I have tried everything available about this issue on internet and even tried the method explained in mdn docs, i cant even extract route path so i can parse the query paramters.
I am just confused why i cant extract even though its visible in the console.log.

this is the API: app/api/getDepratments

export async function GET(req: NextRequest) {
// const name = req.query.hello as string;
// const { searchParams } = new URL(request.url);

const searchParams = req.nextUrl.searchParams
const query = searchParams.get('query') as String

console.log('child_category_query-----|', req.nextUrl, '||hererer', query);


this is whats printed in server console:
GET /api/getDepartments?query=safsf&page=awerwdsfs&limit=10 200 in 306ms
child_category_query-----| NextURL {
[Symbol(NextURLInternal)]: {
url: URL {
href: 'http://localhost:3000/api/getDepartments?query=safsf&page=awerwdsfs&limit=10',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/api/getDepartments',
search: '?query=safsf&page=awerwdsfs&limit=10',
searchParams: URLSearchParams { 'query' => 'safsf', 'page' => 'awerwdsfs', 'limit' => '10' },
hash: ''
},
options: { headers: [Object], nextConfig: undefined },
basePath: '',
domainLocale: undefined,
defaultLocale: undefined,
buildId: undefined,
locale: undefined,
trailingSlash: false
},
[Symbol(searchParams)]: URLSearchParams {}
}
||hererer null
GET /api/getDepartments?query=safsf&page=awerwdsfs&limit=10 200 in 121ms


I just want to get the query parameters, plz help

1 Reply

i tried something like this, it was mentioned dynamic route segments in nexdtjs docs "export async function GET(
req: NextRequest,
{ params }: { params: Promise<{ slug: string }> }
) {

const slug = (await params).slug
console.log('slug here',slug);

const pairs = slug.split('&');

// Create an object to store the parsed values
const parameters = {};

pairs.forEach(pair => {
const [key, value] = pair.split('=');
parameters[key] = value;
});

// Access the values
const query = parameters.query;
const page = parameters.page;
const category = parameters.category;

console.log(query); // Outputs: safsf
console.log(page); // Outputs: awerwdsfs
console.log(category);

const invoices = await fetchChildCategories('department', 'electrical');

return Response.json({ invoices });
}
" and it worked, is this right way and is it safe? i mean we are just embedding the data in the url anyway right?