redirect

This is a shortcut for sending 30x responses.

  1. import { redirect } from "@remix-run/node"; // or cloudflare/deno
  2. export const action = async () => {
  3. const userSession = await getUserSessionOrWhatever();
  4. if (!userSession) {
  5. return redirect("/login");
  6. }
  7. return json({ ok: true });
  8. };

By default, it sends 302, but you can change it to whichever redirect status code you’d like:

  1. redirect(path, 301);
  2. redirect(path, 303);

You can also send a ResponseInit to set headers, like committing a session.

  1. redirect(path, {
  2. headers: {
  3. "Set-Cookie": await commitSession(session),
  4. },
  5. });
  6. redirect(path, {
  7. status: 302,
  8. headers: {
  9. "Set-Cookie": await commitSession(session),
  10. },
  11. });

Of course, you can do redirects without this helper if you’d rather build it up yourself:

  1. // this is a shortcut...
  2. return redirect("/else/where", 303);
  3. // ...for this
  4. return new Response(null, {
  5. status: 303,
  6. headers: {
  7. Location: "/else/where",
  8. },
  9. });

And you can throw redirects to break through the call stack and redirect right away:

  1. if (!session) {
  2. throw redirect("/login", 302);
  3. }