Response Helpers

redirect

Edit this page

Redirects to the next route. When done over a server RPC (Remote Procedure Call), the redirect will be done through the server. By default the status code of a redirect() is 302 - FOUND, also known as a temporary redirect.

Other useful redirect codes:

CodeDescription
301Moved Permanently
307Temporary Redirect
308Permanent redirect

A common use-case for throwing a redirect is when a user is not authenticated and needs to be sent to the login page or another public route.

/queries/get-user.ts
import { query, redirect } from "@solidjs/router";
import { getCurrentUser } from "../auth";
const getUser = query(() => {
const user = await getCurrentUser();
if (!user) throw redirect("/login");
return user;
}, "get-user")

Single-Flight Mutations

When using redirect during a Server Action, the redirect will be done through the server. The response value will automatically send data for the destination route, avoiding a subsequent roundtrip to load the data from the target route.

This is useful when redirecting the user to a different route once a mutation is done.

/actions/add-user.ts
import { action, redirect } from "@solidjs/router";
const addUser = action(async (user: User) => {
await postUser(user);
return redirect("/users");
});

The addUser action will redirect the user to the /users route once the user has been added to the database. The response from the form action will send the updated data for the /users route without the developer needing to revalidate or reload.


Throw vs Return

Both throw and return can be used to redirect the user to a different route. For general usage throw is recommended as it immediately stops the execution of the current action and redirects the user.

When returning from a nested method, the parent method will continue to execute, which can lead to unexpected behavior.

TypeScript Signature

interface ResponseOptions & Omit<ResponseInit, "body"> {
revalidate?: string | string[];
} | number
function redirect(url: string, opts = 302): CustomResponse<never>;

The ResponseOptions extens the types from the native ResponseInit interface.

Report an issue with this page