main
Branches
main (2.16.8)dev
Versions
2.16.81.19.3v0.21.0
React Router v7 has been released. View the docs
redirect

redirect

This is a shortcut for sending 30x responses.

import { redirect } from "@remix-run/node"; // or cloudflare/deno  export const action = async () => {  const userSession = await getUserSessionOrWhatever();   if (!userSession) {  return redirect("/login");  }   return json({ ok: true }); }; 

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

redirect(path, 301); redirect(path, 303); 

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

redirect(path, {  headers: {  "Set-Cookie": await commitSession(session),  }, });  redirect(path, {  status: 302,  headers: {  "Set-Cookie": await commitSession(session),  }, }); 

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

// this is a shortcut... return redirect("/else/where", 303);  // ...for this return new Response(null, {  status: 303,  headers: {  Location: "/else/where",  }, }); 

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

if (!session) {  throw redirect("/login", 302); } 
Docs and examples licensed under MIT