Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
next-safe-navigation
Advanced tools
Static type and runtime validation for navigating routes in NextJS App Router with Zod schemas.
Static and runtime validation of routes, route params and query string parameters on client and server components.
Safe NextJS Navigation is available as a package on NPM, install with your favorite package manager:
npm install next-safe-navigation
[!TIP] Enable
experimental.typedRoutes
innext.config.js
for a better and safer experience with autocomplete when defining your routes
// 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(),
}),
}),
}),
);
[!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 withURLSearchParams
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 inferparams
orsearchParams
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>
)
};
// 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>
)
};
FAQs
Type-safe navigation for NextJS App router
The npm package next-safe-navigation receives a total of 792 weekly downloads. As such, next-safe-navigation popularity was classified as not popular.
We found that next-safe-navigation demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.