Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions packages/react-router/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -617,7 +617,9 @@ function validateSearch(validateSearch: AnyValidator, input: unknown): unknown {
throw new SearchParamError('Async validation not supported')

if (result.issues)
throw new SearchParamError(JSON.stringify(result.issues, undefined, 2))
throw new SearchParamError(JSON.stringify(result.issues, undefined, 2), {
cause: result,
})

return result.value
}
Expand Down Expand Up @@ -1261,9 +1263,12 @@ export class Router<
undefined,
]
} catch (err: any) {
const searchParamError = new SearchParamError(err.message, {
cause: err,
})
let searchParamError = err
if (!(err instanceof SearchParamError)) {
searchParamError = new SearchParamError(err.message, {
cause: err,
})
}

if (opts?.throwOnError) {
throw searchParamError
Expand Down
95 changes: 94 additions & 1 deletion packages/react-router/tests/router.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,21 @@ import {
Link,
Outlet,
RouterProvider,
SearchParamError,
createMemoryHistory,
createRootRoute,
createRoute,
createRouter,
useNavigate,
} from '../src'
import type { AnyRoute, AnyRouter, RouterOptions } from '../src'
import type { StandardSchemaValidator } from '../src/validators'
import type {
AnyRoute,
AnyRouter,
RouterOptions,
ValidatorFn,
ValidatorObj,
} from '../src'

afterEach(() => {
vi.resetAllMocks()
Expand Down Expand Up @@ -1017,6 +1025,91 @@ describe('search params in URL', () => {
await checkSearch({ default: 'd2', optional: 'o1' })
})
})

describe('validates search params', () => {
class TestValidationError extends Error {
issues: Array<{ message: string }>
constructor(issues: Array<{ message: string }>) {
super('validation failed')
this.name = 'TestValidationError'
this.issues = issues
}
}
const testCases: [
StandardSchemaValidator<Record<string, unknown>, { search: string }>,
ValidatorFn<Record<string, unknown>, { search: string }>,
ValidatorObj<Record<string, unknown>, { search: string }>,
] = [
{
['~standard']: {
validate: (input) => {
const result = z.object({ search: z.string() }).safeParse(input)
if (result.success) {
return { value: result.data }
}
return new TestValidationError(result.error.issues)
},
},
},
({ search }) => {
if (typeof search !== 'string') {
throw new TestValidationError([
{ message: 'search must be a string' },
])
}
return { search }
},
{
parse: ({ search }) => {
if (typeof search !== 'string') {
throw new TestValidationError([
{ message: 'search must be a string' },
])
}
return { search }
},
},
]

describe.each(testCases)('search param validation', (validateSearch) => {
it('does not throw an error when the search param is valid', async () => {
let errorSpy: Error | undefined
const rootRoute = createRootRoute({
validateSearch,
errorComponent: ({ error }) => {
errorSpy = error
},
})

const history = createMemoryHistory({
initialEntries: ['/search?search=foo'],
})
const router = createRouter({ routeTree: rootRoute, history })
render(<RouterProvider router={router} />)
await act(() => router.load())

expect(errorSpy).toBeUndefined()
})

it('throws an error when the search param is not valid', async () => {
let errorSpy: Error | undefined
const rootRoute = createRootRoute({
validateSearch,
errorComponent: ({ error }) => {
errorSpy = error
},
})

const history = createMemoryHistory({ initialEntries: ['/search'] })
const router = createRouter({ routeTree: rootRoute, history })
render(<RouterProvider router={router} />)
await act(() => router.load())

expect(errorSpy).toBeInstanceOf(SearchParamError)
expect(errorSpy?.cause).toBeInstanceOf(TestValidationError)
})
})
})
})

describe('route ids should be consistent after rebuilding the route tree', () => {
Expand Down
Loading