How to Use Redirect in Loader in Remix: Simple Guide
In Remix, you use the
redirect function inside a loader to send users to another route before rendering. Simply import redirect from @remix-run/node and return it with the target URL inside your loader.Syntax
The redirect function is imported from @remix-run/node. Inside your loader, you return redirect(<url>) where <url> is the path you want to send the user to.
This stops the loader from rendering the current route and sends the browser to the new location.
javascript
import { redirect } from '@remix-run/node'; export async function loader() { return redirect('/target-path'); }
Example
This example shows a loader that redirects users from /old-page to /new-page. When a user visits /old-page, they are immediately sent to /new-page.
javascript
import { redirect } from '@remix-run/node'; export async function loader() { // Redirect user to /new-page return redirect('/new-page'); } export default function OldPage() { // This component will never render because of the redirect return <p>If you see this, redirect did not work.</p>; }
Output
User is redirected to /new-page immediately when visiting /old-page.
Common Pitfalls
- Not importing
redirect: Forgetting to importredirectcauses errors. - Returning a string instead of
redirect(): Returning just a URL string does not trigger a redirect. - Using redirect in component instead of loader: Redirects must happen in loaders or actions, not inside React components.
javascript
/* Wrong way: returning string */ export async function loader() { return '/new-page'; // This does NOT redirect } /* Right way: returning redirect */ import { redirect } from '@remix-run/node'; export async function loader() { return redirect('/new-page'); }
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Import redirect | import { redirect } from '@remix-run/node'; | Required to use redirect function |
| Return redirect | return redirect('/path'); | Triggers HTTP redirect response |
| Use in loader or action | export async function loader() { return redirect('/'); } | Redirects before rendering |
| Do not use in component | N/A | Redirects must be server-side in loader/action |
Key Takeaways
Always import and return the redirect function from @remix-run/node inside your loader.
Returning redirect stops the current route and sends the user to the new URL immediately.
Redirects must happen in loaders or actions, not inside React components.
Returning a plain string URL does not cause a redirect.
Use redirect to handle route changes before the page renders for smooth navigation.