author avatar

aman.suhag

Mon Sep 30 2024

Understanding context.params and req.nextUrl.searchParams() in Next.js

  1. context.params for Dynamic Routes In Next.js, dynamic routes are created by using brackets in the file names inside the pages directory (or in the /app directory in the case of the App Router). For example, if you create a file called [id].js, you are creating a dynamic route where id is a parameter. Example:
const { id } = context.params;
  1. req.nextUrl.searchParams() for Query Strings Query strings are parameters passed through the URL, typically after a ? symbol. These are useful for handling additional data or filters that don’t affect the route structure. In Next.js, with the App Router or when using API routes, you can use req.nextUrl.searchParams() to access query parameters. Example:
const searchParams = req.nextUrl.searchParams;
const searchTerm = searchParams.get('query'); // ?query=nextjs

Key Differences:

Dynamic Routes (context.params) are part of the URL path, like /product/123, where 123 is dynamically extracted. • Query Strings (req.nextUrl.searchParams) are optional parameters passed in the URL, like /api/search?query=nextjs. Both are useful depending on whether you want to make the parameters part of the URL path or pass them as additional optional information. #nextJS #query #dynamic-params