vasepa
v1.0.1
Published
An easier way to validate search params.
Downloads
22
Readme
vasepa
An easier way to validate search params.
Example Usage
Example for a /dashboard/transactions page in Next JS 15.
Create a schema with zod and allow month and year as search params.
If any values do not pass the validation in the schema, redirect the user to the same page but with updated query string containing valid values, set by .catch in the schema.
Based on the below implementation, trying to navigate to /dashboard/transactions?month=1000&year=bob will redirect the user to /dashboard/transactions?month=1&year=2025 (assuming the current month is January and the current year is 2025).
Similarly trying to navigate to /dashboard/transactions?myname=jeff will redirect the user to /dashboard/transactions because myname is not defined in the search schema.
For convenience, validateSearchParams returns the parsedParams.
// app/dashboard/transactions/page.tsx
import { z } from "zod";
import { validateSearchParams } from "vasepa";
const today = new Date();
const searchSchema = z.object({
month: z.coerce
.number()
.min(1)
.max(12)
.catch(today.getMonth() + 1),
year: z.coerce
.number()
.max(today.getFullYear())
.min(today.getFullYear() - 100)
.catch(today.getFullYear()),
});
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ year: string; month: string }>;
}) {
const searchParamsValues = await searchParams;
const parsedSearchParams = searchSchema.parse(searchParamsValues);
const { month, year } = validateSearchParams({
rawParams: searchParamsValues,
parsedParams: parsedSearchParams,
onInvalidParams: (validQueryString) => {
redirect(`/dashboard/transactions${validQueryString}`);
},
});
return <div>page content</div>;
}