T
TanStack2d ago
unwilling-turquoise

No redirection using throw redirect in middleware

Hello, there is something I don't understand, below is my setup, why the redirect does not work ?? I just get an error on my ErrorCatchBoundary. It is like the error is not handled by the router lifecycle, but I don't understand why....
// My dashboard route
export const Route = createFileRoute("/_admin/admin/_layout/dashboard")({
loader: async ({ context: { queryClient } }) => {
return queryClient.ensureQueryData(adminOverviewOptions());
},
component: DashboardPage,
});

// The query option with the server function
export const adminOverviewOptions = () => queryOptions({
queryKey: adminQueryKeys.adminOverviewKey(),
queryFn: () => getAdminOverview(),
});

// The server function with the middlewares
export const getAdminOverview = createServerFn({ method: "GET" })
.middleware([managerAuthMiddleware, adminAuthMiddleware])
.handler(async () => {
const userService = await getContainer().then((c) => c.services.user);
return userService.getAdminOverview();
});

// The admin middleware which check the token, if bad token should redirect to "/admin"
export const adminAuthMiddleware = createMiddleware({ type: "function" }).server(async ({ next }) => {
const adminToken = getCookie(ADMIN_COOKIE_NAME);

if (!adminToken || !verifyAdminToken(adminToken)) {
throw redirect({ to: "/admin" });
}

return next();
});
// My dashboard route
export const Route = createFileRoute("/_admin/admin/_layout/dashboard")({
loader: async ({ context: { queryClient } }) => {
return queryClient.ensureQueryData(adminOverviewOptions());
},
component: DashboardPage,
});

// The query option with the server function
export const adminOverviewOptions = () => queryOptions({
queryKey: adminQueryKeys.adminOverviewKey(),
queryFn: () => getAdminOverview(),
});

// The server function with the middlewares
export const getAdminOverview = createServerFn({ method: "GET" })
.middleware([managerAuthMiddleware, adminAuthMiddleware])
.handler(async () => {
const userService = await getContainer().then((c) => c.services.user);
return userService.getAdminOverview();
});

// The admin middleware which check the token, if bad token should redirect to "/admin"
export const adminAuthMiddleware = createMiddleware({ type: "function" }).server(async ({ next }) => {
const adminToken = getCookie(ADMIN_COOKIE_NAME);

if (!adminToken || !verifyAdminToken(adminToken)) {
throw redirect({ to: "/admin" });
}

return next();
});
when the throw redirect is hit i just get my "An error occurred page" instead of a redirection. (I'm using SPA mode, defaultSsr to false in router and a shell component for information). Thanks in advance :).
2 Replies
continuing-cyan
continuing-cyan2d ago
can you please create a GitHub issue including a complete minimal example for this?
unwilling-turquoise
unwilling-turquoiseOP8h ago
I can try but in the mean time I can show you the results of my global error middleware when I console log the object:
export const errorMiddleware = createMiddleware({ type: "function" }).server(async ({ next }) => {
const results = await next();
console.log({ results });
return results;
}
export const errorMiddleware = createMiddleware({ type: "function" }).server(async ({ next }) => {
const results = await next();
console.log({ results });
return results;
}
When I have a redirection in a middleware I got a Response 307 object.
{
results: {
url: '/_serverFn/src_lib_server_functions_user-profile_ts--getUserProfile_createServerFn_handler',
functionId: 'src_lib_server_functions_user-profile_ts--getUserProfile_createServerFn_handler',
data: { username: 'Cross' },
context: {},
type: undefined,
signal: AbortSignal { aborted: false },
headers: Headers {},
sendContext: {},
result: undefined,
error: Response {
status: 307,
statusText: '',
headers: Headers {},
body: null,
bodyUsed: false,
ok: false,
redirected: false,
type: 'default',
url: ''
}
}
}
{
results: {
url: '/_serverFn/src_lib_server_functions_user-profile_ts--getUserProfile_createServerFn_handler',
functionId: 'src_lib_server_functions_user-profile_ts--getUserProfile_createServerFn_handler',
data: { username: 'Cross' },
context: {},
type: undefined,
signal: AbortSignal { aborted: false },
headers: Headers {},
sendContext: {},
result: undefined,
error: Response {
status: 307,
statusText: '',
headers: Headers {},
body: null,
bodyUsed: false,
ok: false,
redirected: false,
type: 'default',
url: ''
}
}
}
whereas the notFound works as expected and the returned data are:
{
results: {
url: '/_serverFn/src_lib_server_functions_user-profile_ts--getUserProfile_createServerFn_handler',
functionId: 'src_lib_server_functions_user-profile_ts--getUserProfile_createServerFn_handler',
data: { username: '...' },
context: {},
type: undefined,
signal: AbortSignal { aborted: false },
headers: Headers {},
sendContext: {},
result: undefined,
error: { isNotFound: true }
}
}
{
results: {
url: '/_serverFn/src_lib_server_functions_user-profile_ts--getUserProfile_createServerFn_handler',
functionId: 'src_lib_server_functions_user-profile_ts--getUserProfile_createServerFn_handler',
data: { username: '...' },
context: {},
type: undefined,
signal: AbortSignal { aborted: false },
headers: Headers {},
sendContext: {},
result: undefined,
error: { isNotFound: true }
}
}

Did you find this page helpful?