AGENT SKILL

nuqs-url-state

nuqs URL state management patterns for Next.js App Router. Activate when reading or writing URL search params, building filters, pagination, tabs, or any state that should live in the URL.

License 许可
MIT
最近更新
2026-10-23
Stars
★ 1
Forks
0

01 前言 Front Matter

name
nuqs-url-state
description
nuqs URL state management patterns for Next.js App Router. Activate when reading or writing URL search params, building filters, pagination, tabs, or any state that should live in the URL.

03 SKILL.md 正文

nuqs URL State Patterns

nuqs provides type-safe URL search param state for Next.js App Router. Use it for any state that should be shareable, bookmarkable, or survive a page refresh.

When to Apply

  • Filter panels, search inputs, sort controls
  • Pagination (page, pageSize)
  • Tabs or view mode toggles that should be deep-linkable
  • Any state where "copy the URL" should reproduce the current view

Do NOT use nuqs for ephemeral UI state (modals, hover states, transient animations). Use useState for those.

Core Rules

1. Always pair with a Zod schema for validation

nuqs parsers validate on parse, but complex shapes need explicit Zod schemas at the service boundary.

// BAD — raw string, no validation
const [sort] = useQueryState('sort');

// GOOD — typed parser
import { parseAsStringLiteral } from 'nuqs';
const SORT_OPTIONS = ['asc', 'desc'] as const;
const [sort, setSort] = useQueryState('sort', parseAsStringLiteral(SORT_OPTIONS).withDefault('asc'));

2. Use useQueryStates for related params

Group related params to avoid race conditions and unnecessary re-renders.

// BAD — two separate hooks, two URL updates
const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1));
const [search, setSearch] = useQueryState('search', parseAsString.withDefault(''));

// GOOD — atomic update
const [params, setParams] = useQueryStates({
  page: parseAsInteger.withDefault(1),
  search: parseAsString.withDefault(''),
});

3. Reset page when filters change

When filters update, page must reset to 1 in the same atomic call.

const handleSearchChange = (search: string) => {
  setParams({ search, page: 1 }); // reset together
};

4. Use shallow: false only when SSR needs to re-run

By default nuqs uses shallow routing (no server round-trip). Set shallow: false only when changing params must trigger a Server Component re-render (e.g., server-side filtered data).

const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1).withOptions({ shallow: false }));

5. Server Components: use searchParams prop, not useQueryState

useQueryState is a client hook. In Server Components, read params from the searchParams prop directly and validate with a Zod schema.

Route where the search parameters parsing is needed, should create a searchParams.ts file and export a loader that describes schema:

// src/app/products/searchParams.ts
import { createLoader, parseAsInteger, parseAsString } from 'nuqs/server';

export const loadProductsSearchParams = createLoader({
    page: parseAsInteger.withDefault(1),
    search: parseAsString.withDefault(''),
});
// app/products/page.tsx (Server Component)
import type { NextPage } from 'next';
import { loadProductsSearchParams } from './searchParams';

const Page: NextPage<{ searchParams: Promise<Record<string, string>> }> = ({ searchParams }) => {
  const awaitedSearchParams = await loadProductsSearchParams(searchParams);
  // pass parsed to prefetchQuery or directly to RSC data fetching
}

export default Page;

6. Define parsers as constants, not inline

Inline parser definitions recreate objects on every render. Repetitive parsers should be hoisted to global search params scope at src/lib/searchParams/client.ts and src/lib/searchParams/server.ts. Client and server should have the same parsers. CLient ones are applicable in client component only. Server ones are applicable in src/app/*/searchParams.ts files and in client component if createSearchParamsCache constant is used.

// BAD
const [page] = useQueryState('page', parseAsInteger.withDefault(1));

// GOOD — hoist to module scope
import { parseAsPage } from '@/lib/searchParams/client';

const [page] = useQueryState('page', parseAsPage);

7. Use createSearchParamsCache for RSC + client sync

When the same params are read in both Server and Client Components, use createSearchParamsCache to avoid duplication.

// src/lib/searchParams/server.ts
import { createSearchParamsCache, parseAsInteger, parseAsString } from 'nuqs/server';

export const productSearchParamsCache = createSearchParamsCache({
  page: parseAsPage,
  search: parseAsString.withDefault(''),
});
export type ProductSearchParams = ReturnType<typeof productSearchParamsCache.parse>;
// In Server Component layout or page:
productSearchParamsCache.parse(searchParams);

// In Client Component:
import { useQueryStates } from 'nuqs';
import { productSearchParamsCache } from '@/lib/searchParams/server';
const [params] = useQueryStates(productSearchParamsCache.parsers);

Common Parsers Reference

Data type Parser
String parseAsString
Integer parseAsInteger
Float parseAsFloat
Boolean parseAsBoolean
String enum parseAsStringLiteral(['a', 'b'])
JSON object parseAsJson(zodSchema.parse)
Array parseAsArrayOf(parseAsString)
ISO date parseAsIsoDateTime

Integration with TanStack Query

Pass nuqs params into query options directly — they are already stable primitives.

const [params] = useQueryStates(productSearchParamsCache.parsers);
const { data } = useQuery(productsQueryOptions(params));

Invalidation does not need to touch nuqs — query keys derived from params will naturally update when params change.

04 同仓库更多 Skills

Phenomenon-Studio
Phenomenon-Studio/phenomenon-configs

web-security

Enforce web security and avoid security vulnerabilities.

★ 1
Phenomenon-Studio
Phenomenon-Studio/phenomenon-configs

typescript

Write clean, efficient TypeScript code that follows project conventions and advanced type patterns. Use when writing or reviewing TypeScript code, defining types, creating generics, handling errors, or working with React components, Zod schemas, and TanStack libraries.

★ 1
Phenomenon-Studio
Phenomenon-Studio/phenomenon-configs

tanstack-router

TanStack Router patterns for this repo — file-based routing, auth guards, search params, data loading, TanStack Query integration, navigation, and code splitting. Use when creating routes, adding pages, implementing auth flows, working with search/path params, or integrating loaders with TanStack Query.

★ 1
Phenomenon-Studio
Phenomenon-Studio/phenomenon-configs

tanstack-query

TanStack Query patterns for this repo — queryOptions/mutationOptions factories, query key hierarchies, service layer integration, optimistic updates, Suspense usage, error handling, and TanStack Router data loading. Use when creating queries, mutations, API services, query keys, cache invalidation, optimistic updates, or integrating data fetching with routes.

★ 1
Phenomenon-Studio
Phenomenon-Studio/phenomenon-configs

tanstack-form

Build forms using TanStack Form with the project's useAppForm composition, composable field components, Zod validation schemas, FormFieldWrapper error tracking, and form.AppField vs form.Field patterns. Use when creating new forms, adding form fields, writing form validation, or working with TanStack Form in this project.

★ 1
Phenomenon-Studio
Phenomenon-Studio/phenomenon-configs

react

Build clean, modern React components that apply common best practices and avoid common pitfalls like unnecessary state management or useEffect usage.

★ 1