redirect
redirect is a response helper that returns a Response object object that instructs the router to navigate to a different route when returned or thrown from a query or action.
Import
import { redirect } from "@solidjs/router";Type
type RouterResponseInit = Omit<ResponseInit, "body"> & { revalidate?: string | string[];};
function redirect( url: string, init?: | number | { revalidate?: string | string[]; headers?: HeadersInit; status?: number; statusText?: string; }): CustomResponse<never>;Parameters
url
- Type:
string - Required: Yes
The absolute or relative URL to which the redirect should occur.
init
- Type:
number | RouterResponseInit - Default:
302 - Required: No
Redirect status code or response options.
revalidate
- Type:
string | string[] - Required: No
Key or keys written to the X-Revalidate response header.
status
- Type:
number - Required: No
The HTTP status code for the redirect.
Defaults to 302 Found).
Return value
- Type:
CustomResponse<never>
Returns a Response object with a Location header.
Behavior
- A numeric
initis used as the response status. - Object
initvalues defaultstatusto302whenstatusis undefined. - Writes
urlto theLocationheader. - Defined
revalidatevalues are written to theX-Revalidateheader withtoString().
Examples
Basic usage
import { query, redirect } from "@solidjs/router";
const getCurrentUser = query(async () => { const response = await fetch("/api/me");
if (response.status === 401) { return redirect("/login"); }
return response.json();}, "currentUser");