T
TanStack6mo ago
fascinating-indigo

zod schema for redirect

Does Tanstack Router generate a schema for zod to validate the routes? If not, could it? My thought is to use for a redirect parameter
6 Replies
fascinating-indigo
fascinating-indigoOP6mo ago
If anyone is interested, I solved this by:
import { type UnionToTuple } from 'type-fest';
import { z } from 'zod';

import { router } from './router';
import { type FileRouteTypes } from './routeTree.gen';

// Note we're using the `to` property from the `FileRouteTypes` type
// because it lacks the trailing slashes as per the runtime behaviour of `router.routesByPath`
//
type FilePathRoutes = UnionToTuple<'.' | '..' | FileRouteTypes['to']>;

export const FilePathsSchema = () => z.enum(Object.keys(router.routesByPath) as unknown as FilePathRoutes);
import { type UnionToTuple } from 'type-fest';
import { z } from 'zod';

import { router } from './router';
import { type FileRouteTypes } from './routeTree.gen';

// Note we're using the `to` property from the `FileRouteTypes` type
// because it lacks the trailing slashes as per the runtime behaviour of `router.routesByPath`
//
type FilePathRoutes = UnionToTuple<'.' | '..' | FileRouteTypes['to']>;

export const FilePathsSchema = () => z.enum(Object.keys(router.routesByPath) as unknown as FilePathRoutes);
and
get validateSearch() {
return zodValidator(
z.object({
redirect: FilePathsSchema().optional(),
}),
);
},
get validateSearch() {
return zodValidator(
z.object({
redirect: FilePathsSchema().optional(),
}),
);
},
You'll notice I didn't use the tying of router.routesByPath becaue there's a small bug in the types, where it doesn't match the runtime behaviour
sunny-green
sunny-green6mo ago
which bug?
fascinating-indigo
fascinating-indigoOP6mo ago
GitHub
Generated type FileRoutesByFullPath doesn't match runtime type · Is...
Which project does this relate to? Router Describe the bug Problem router.routesByPath is defined as RoutesByPath<TRouteTree> which includes trailing '/' for index routes. However thi...
sunny-green
sunny-green6mo ago
fyi we have a trailingSlash prop on createRouter, so you could make the types work if you set it to always just as a workaround for the time being
fascinating-indigo
fascinating-indigoOP6mo ago
I don't mind, as I'm aware. Seems like a fairly easy fix
sunny-green
sunny-green6mo ago
not really as the code generation and createRouter are not coupled

Did you find this page helpful?