redirect
Edit this pageRedirects 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:
| Code | Description |
|---|---|
301 | Moved Permanently |
307 | Temporary Redirect |
308 | Permanent redirect |
307 and 308 won't allow the browser to change the method of the request. If you want to change the method, you should use 301 or 302.
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.
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.
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
type RouterResponseInit = Omit<ResponseInit, "body"> & { revalidate?: string | string[];};
function redirect(url: string, init?: number | RouterResponseInit): CustomResponse<never>;The RouterResponseInit type extends the native ResponseInit interface.
Revalidate Query Keys
You can pass query keys to the redirect helper to revalidate them.
redirect("/", { revalidate: ["getUser", getUser.keyFor(id)] });This will only invalidate the query keys passed to the redirect helper instead of the entire next page.