[Solved] Redirecting to Origin URL with Next.js Route Not Working – Next.js

by
Alexei Petrov
next.js next.js13 react-typescript reactjs supabase

The Problem:

A user is experiencing issues implementing a logout feature in a Next.js application. Clicking the logout button is calling the server-side route, but the user is not being redirected to the origin page as expected. The server logs show a "Status: 200 OK" response, but the redirect is not occurring. The user verified the origin URL and HTTP method, and checked for common issues, but the problem persists.

The Solutions:

Solution 1: Redirect on Browser Side

The Next.js redirect function is used to perform client-side redirects. In contrast, NextResponse.redirect is utilized for server-side redirects. When you want to redirect the user’s browser to a different page, you should employ redirect.

To resolve your issue, modify your code as follows:

import { redirect } from 'next/navigation';

export default async function Profile({ shouldRedirect }) {
  if (shouldRedirect) {
    redirect('/');
  }
  // ...
}

This code checks if shouldRedirect is true and, if so, initiates a redirect to the root URL (‘/’) on the client side. This should successfully redirect the user’s browser as desired.

Q&A

What is the difference between redirect on browser and server ?

Browser-side redirects are handled by browsers and happen on the client side, while server-side redirects are handled by the server and happen on the server side.

Video Explanation:

The following video, titled "Next.js Middleware & Cors | Nextjs 13 tutorial - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Web Dev Roadmap for Beginners (Free!): https://bit.ly/DaveGrayWebDevRoadmap Learn how to apply Next.js middleware in Nextjs 13.