Reactbeginner

Redirect

A function that sends the user to a different page after a successful action, like navigating to a post after creating it.

Detailed Explanation

Redirect is a navigation technique used in React Router to send the user to a different Route after an action completes successfully. Instead of returning data to the component, the action returns a redirect response that tells the browser to navigate somewhere else.

import { redirect } from 'react-router-dom';

export async function action({ request }) {
  const formData = await request.formData();
  const { data, error } = await supabase.from('posts').insert({...}).select().single();
  if (error) return { error: error.message };
  return redirect(`/posts/${data.id}`);
}

The common pattern is: return data for errors, redirect for success. When Validation fails or a Database error occurs, the action returns an error object that useActionData displays. When everything succeeds, the action redirects to the new resource (like the newly created post).

Redirect creates an HTTP response with a Status Code of 302 (or 303), which the browser follows automatically. This is different from using navigate() inside a Component — redirect works inside loaders and actions, while navigate works inside components and event handlers.

In OAuth flows, redirects are used to send users to the provider's consent screen and back to an OAuth Callback URL after authentication.

Ready to Build Something Real?

We give you the skills to build, deploy, and own a full product. Professional stack, AI co-pilot, no coding background required.