Server-Side usage
Type-safe search params on the server
Loaders
To parse search params server-side, you can use a loader function.
You create one using the createLoader
function, by passing it your search params
descriptor object:
Here, loadSearchParams
is a function that parses search params and returns
state variables to be consumed server-side (the same state type that useQueryStates
returns).
Note
Loaders don’t validate your data. If you expect positive integers or JSON-encoded objects of a particular shape, you’ll need to feed the result of the loader to a schema validation library, like Zod.
Built-in validation support is coming. Read the RFC. Alternatively, you can build validation into custom parsers.
The loader function will accept the following input types to parse search params from:
- A string containing a fully qualified URL:
https://example.com/?foo=bar
- A string containing just search params:
?foo=bar
(likelocation.search
) - A
URL
object - A
URLSearchParams
object - A
Request
object - A
Record<string, string | string[] | undefined>
(eg:{ foo: 'bar' }
) - A
Promise
of any of the above, in which case it also returns a Promise.
Cache
The next/server/cache
feature is available for Next.js app router only.
If you wish to access the searchParams in a deeply nested Server Component
(ie: not in the Page component), you can use createSearchParamsCache
to do so in a type-safe manner.
Think of it as a loader combined with a way to propagate the parsed values down the RSC tree, like Context would on the client.
Deprecation notice
The cache feature is also accessible from nuqs/server
in nuqs@^2, but
will be removed from that import in nuqs@3.0.0.
Please update your imports to nuqs/server/cache
for a smoother transition.
This is to allow non-Next.js server code to use the nuqs/server
import
without having to install React canary for the cache
function.
The cache will only be valid for the current page render
(see React’s cache
function).
Note: the cache only works for server components, but you may share your
parser declaration with useQueryStates
for type-safety in client components:
Shorter search params keys
Just like useQueryStates
, you can
define a urlKeys
object to map the variable names defined by the parser to
shorter keys in the URL. They will be translated on read and your codebase
can only refer to variable names that make sense for your domain or business logic.