npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-safe-navigation

v0.3.3

Published

Type-safe navigation for NextJS App router

Downloads

3,057

Readme

📦 Install

Safe NextJS Navigation is available as a package on NPM, install with your favorite package manager:

npm install next-safe-navigation

⚡ Quick start

[!TIP] Enable experimental.typedRoutes in next.config.js for a better and safer experience with autocomplete when defining your routes

Declare your application routes and parameters in a single place

// src/shared/navigation.ts
import { createNavigationConfig } from "next-safe-navigation";
import { z } from "zod";

export const { routes, useSafeParams, useSafeSearchParams } = createNavigationConfig(
  (defineRoute) => ({
    home: defineRoute('/'),
    customers: defineRoute('/customers', {
      search: z
        .object({
          query: z.string().default(''),
          page: z.coerce.number().default(1),
        })
        .default({ query: '', page: 1 }),
    }),
    invoice: defineRoute('/invoices/[invoiceId]', {
      params: z.object({
        invoiceId: z.string(),
      }),
    }),
    shop: defineRoute('/support/[...tickets]', {
      params: z.object({
        tickets: z.array(z.string()),
      }),
    }),
    shop: defineRoute('/shop/[[...slug]]', {
      params: z.object({
        // ⚠️ Remember to always set your optional catch-all segments
        // as optional values, or add a default value to them
        slug: z.array(z.string()).optional(),
      }),
    }),
  }),
);

Runtime validation for React Server Components (RSC)

[!IMPORTANT] The output of a Zod schema might not be the same as its input, since schemas can transform the values during parsing (e.g.: z.coerce.number()), especially when dealing with URLSearchParams where all values are strings and you might want to convert params to different types. For this reason, this package does not expose types to infer params or searchParams from your declared routes to be used in page props:

interface CustomersPageProps {
  // ❌ Do not declare your params | searchParam types
  searchParams?: ReturnType<typeof routes.customers.$parseSearchParams>
}

Instead, it is strongly advised that you parse the params in your server components to have runtime validated and accurate type information for the values in your app.

// src/app/customers/page.tsx
import { routes } from "@/shared/navigation";

interface CustomersPageProps {
  // ✅ Never assume the types of your params before validation
  searchParams?: unknown
}

export default async function CustomersPage({ searchParams }: CustomersPageProps) {
  const { query, page } = routes.customers.$parseSearchParams(searchParams);

  const customers = await fetchCustomers({ query, page });

  return (
    <main>
      <input name="query" type="search" defaultValue={query} />

      <Customers data={customers} />
    </main>
  )
};

/* --------------------------------- */

// src/app/invoices/[invoiceId]/page.tsx
import { routes } from "@/shared/navigation";

interface InvoicePageProps {
  // ✅ Never assume the types of your params before validation
  params?: unknown
}

export default async function InvoicePage({ params }: InvoicePageProps) {
  const { invoiceId } = routes.invoice.$parseParams(params);

  const invoice = await fetchInvoice(invoiceId);

  return (
    <main>
      <Invoice data={customers} />
    </main>
  )
};

Runtime validation for Client Components

// src/app/customers/page.tsx
'use client';

import { useSafeSearchParams } from "@/shared/navigation";

export default function CustomersPage() {
  const { query, page } = useSafeSearchParams('customers');

  const customers = useSuspenseQuery({
    queryKey: ['customers', { query, page }],
    queryFn: () => fetchCustomers({ query, page}),
  });

  return (
    <main>
      <input name="query" type="search" defaultValue={query} />

      <Customers data={customers.data} />
    </main>
  )
};

/* --------------------------------- */

// src/app/invoices/[invoiceId]/page.tsx
'use client';

import { useSafeParams } from "@/shared/navigation";

export default function InvoicePage() {
  const { invoiceId } = useSafeParams('invoice');

  const invoice = useSuspenseQuery({
    queryKey: ['invoices', { invoiceId }],
    queryFn: () => fetchInvoice(invoiceId),
  });

  return (
    <main>
      <Invoice data={invoice.data} />
    </main>
  )
};

Use throughout your codebase as the single source for navigating between routes:

import { routes } from "@/shared/navigation";

export function Header() {
  return (
    <nav>
      <Link href={routes.home()}>Home</Link>
      <Link href={routes.customers()}>Customers</Link>
    </nav>
  )
};

export function CustomerInvoices({ invoices }) {
  return (
    <ul>
      {invoices.map(invoice => (
        <li key={invoice.id}>
          <Link href={routes.invoice({ invoiceId: invoice.id })}>
            View invoice
          </Link>
        </li>
      ))}
    </ul>
  )
};