Navigating between different route groups using redirection: a step-by-step guide

My project folder structure is organized like this:

  • app
    • (app)
      • dashboard
        • page.tsx
      • page.tsx
      • layout.tsx
    • (auth)
      • login
        • page.tsx
      • register
        • page.tsx
      • page.tsx
      • layout.tsx

I can easily move between the login and register pages using the redirect method (from next/navigation). However, I am facing issues redirecting to the dashboard page as well as redirecting from the dashboard to login or register.

P/s: Although I can navigate using useRouter().push, I prefer using the redirect method because the redirection logic is server-side.

P/s: Upon executing the redirect, my terminal logs show POST / 303 but nothing happens.

Here is the updated code where I redirect from "/" to the login page:

import { redirect } from "next/navigation";

export default function Root({ children }: { children: React.ReactNode }) {
  return (
    <div>
      <form
        action={async () => {
          "use server";
          redirect("/login");
        }}
      >
        <button>Go to login</button>
      </form>
      <p>Root Page</p>
    </div>
  );
}

Answer №1

To make your Root component redirect to the login page when the button is clicked, you can update it as follows:

import { useRouter } from 'next/router';

export default function Root({ children }: { children: React.ReactNode }) {
  const router = useRouter();

  const handleClick = () => {
    router.push('/login');
  };

  return (
    <div>
      <button onClick={handleClick}>Go to login</button>
      <p>Root Page</p>
    </div>
  );
}

If you need to perform a server-side redirect, you should include it in either getServerSideProps or getInitialProps. Here is an example of performing a server-side redirect using getServerSideProps:

export async function getServerSideProps(context) {
  return {
    redirect: {
      destination: '/login',
      permanent: false,
    },
  }
}

This configuration will redirect all requests for this page to the login page. Keep in mind that this is a server-side redirect, so it will occur before the page is sent to the client.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switching between rows in a table once information has been added to an array | Vue

I'm currently working on creating a table with rows that toggle when a 'View' button is clicked. The table is generated using a for loop for an array. I've successfully implemented the toggling functionality for preloaded data, but enco ...

Update WooCommerce Mini-cart with ajax refresh

I'm having an issue with my custom plugin where everything is working properly, except for the fact that the mini cart is not updating after adding items. I have tried various methods to trigger a refresh, but so far nothing has worked. Below is a sni ...

How to effectively manage Mongoose Query Exceptions in Express.js

Let's imagine a scenario where I need to execute a Mongoose query in an Express post route: app.post("/login",(req,res)=>{ const username = req.body.username const password = req.body.password User.find({username:username},(er ...

Version 4.6.4 of TypeScript is flagging the code as invalid

How can I fix this Typescript problem? const userInformation: { email: string; id: string; _token: string; _tokenExpirationDate: string; } = JSON.parse(localStorage.getItem('userData')); https://i.sstatic.net/xMh9P.pn ...

Retrieve the nearest identifier text from the tables

I have a table on my webpage with some data: <tbody id="carga"> <tr> <td>1</td> <td id="nombre">esteban</td> <td id="apellido">aguirre</td> <td>N/A</td> <td>N/A</td ...

Error encountered during Yarn installation process: The tunneling socket was unable to be established due to a connection refusal on localhost at port 80

I have a Next.js app that needs to be built on our company servers before deployment. We use a proxy, and I've configured yarn to use the proxy as well. yarn config set proxy http://xx.xxx.xx:xxxx yarn config set httpsProxy http://xx.xxx.xx:xxxx yarn ...

PHP variable missing "+" sign at the end after post operation

I have encountered a unique problem that I cannot seem to find anywhere else. My issue lies in adding grades ending with a plus sign, such as B+, C+ or D+. I am able to add grades like A-, B-, C- and D- without any problem, but when it comes to adding a g ...

Implementing Pagination for a JSON Object using Javascript and Jquery

I am looking for the most effective way to implement pagination in my current situation: I am using "$('body').append(htmlText);" to display the items from a JSON object. How can I set up pagination so that each page displays only one item based ...

Troubleshooting Problems with Google Maps and Javascript/JSON in Internet Explorer

Currently, I am utilizing the Google Maps API to construct a map that displays store locations in close proximity to a user-specified location. Everything is functioning properly, however, I am encountering an error in Internet Explorer that I would like t ...

Having trouble loading services within my Angular controller

After developing my Angular application, I added some basic code to my controller which is displayed below. Now, I am attempting to include two services that I created in my services.js file. This file is being loaded in my index.html and required within m ...

Is there a way to filter and tally the JSON objects that have latitude and longitude within a 10km radius from the

I'm currently working on filtering and counting objects from an API endpoint that fall within a 10km radius of the specified origin. My main challenge lies in correctly filtering the API results and tallying the number of matching items. While I succ ...

In what way can I incorporate additional functions or multiple functions within an Express route to modify database information?

Currently, I am working on a project that involves Express and MySQL. One of the challenges I am facing is retrieving data from a connection.query and then utilizing that data in other functions within the same route. My goal is to use the array created in ...

Experiencing an initial rendering problem with Next.js / Nx Nrwl / Material UI styles when deploying to production. Are others facing the same issue as well?

Trying to utilize the nx nrwl with the next js plugin and material ui has been quite the journey. While everything runs smoothly in our development builds, the material-ui/styles seem to break when we deploy the production build. The classes created using ...

Creating a well-aligned form using Material-UI

Exploring Material-UI for the first time! How can a form be built where certain fields are arranged horizontally, others stacked vertically, and all aligned perfectly both vertically and horizontally? Check out this example image: https://i.sstatic.net/5R ...

Is there a way to assign API data as inner HTML using Lit?

Need help setting inner html of html elements with a get request Any suggestions on how to achieve this? import { LitElement, html, css } from "lit"; import { customElement } from "lit/decorators.js"; import axios from "axios" ...

Having trouble importing Bootstrap into Next.js? It seems like the issue may be related to the

I am currently facing an issue with importing bootstrap 5.3.2 (not react-bootstrap) into my NextJS 14.1.0 project that utilizes the new App Router. My goal is to strategically utilize individual Bootstrap components (not through data-attrs). I managed to ...

Node.js Express refuses to serve .js files with absolute URLs

I have encountered a perplexing issue with two files located in /public/widget, namely help.html and help.js http://localhost:8084/widget/help.html When entered into the address bar, it functions normally However, when attempting to access http://local ...

Retrieving information within a Vue component

I am struggling to access some data I have bound to a component without success. How can I achieve this? Below is my component: export default { name: 'component-vallingby', data() { return { } }, created() {}, methods: {} } And h ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

The error message from ReactJS states: "Ensure that this component is only utilized within a <RecoilRoot> component."

However, I am approaching it slightly differently. Instead of using a layout, I have a per page component that I want to integrate into the header. When implementing this, I encounter the following error: https://i.sstatic.net/G7NOp.png In Account.jsx:, ...