Securing nested routes in NextJs with authentication

Is there a way to authenticate all nested routes in my project? Some routes require authentication, while others can be accessed without it. For example:
/admin => requires authentication
/admin/posts => requires authentication
/admin/posts/1 => requires authentication
/admin/users => requires authentication
and so on...
/view => can be accessed without authentication
/view/songs => can be accessed without authentication
/view/posts => can be accessed without authentication
Things I have tried:
HOC: need to include it in every route inside admin. Is there a way to do it in a common place?
getServerSideProps: same as above

Is there a way to achieve this in one common file?

Answer №1

To achieve the desired outcome, there are various approaches you can take with just a few inputs:

If you're utilizing nextJS version 13 or above and adopting the new app directory routing system, you can make use of the layout.js file located in the root of the /admin folder:

 export default function RootLayout({ children }) {
      // Your logic to verify user login status
      if(/* user is logged in */){
          return (
            <html>
              <head></head>
              <body>{children}</body>
            </html>
          )
      }else{
          return <p>Authentication Required</p> // Display Login Form
      }
    }

Alternatively, a similar approach can be implemented within the _App.js:

import { useRouter } from 'next/router';
import {MyAuthComponent} from 'auth/path' // your authentication component

export default function MyApp({ Component, pageProps }) {
    const router = useRouter();
    const currentPath = router.asPath
    const isPublicRoute = currentPath.includes('view') // Logic for public route check
    if(isPublicRoute ){
        return  <Component {...pageProps} />
    }else{
      return (
          <MyAuthComponent>
              <Component {...pageProps} />
          </MyAuthComponent>
      )
    }
}

Lastly, include the MyAuthComponent.js:

 export default function MyAuthComponent({ children }) {
      // Your logic to verify user login status
      if(/* user is logged in */){
          return (
            <html>
              <head></head>
              <body>{children}</body>
            </html>
          )
      }else{
          return <p>Authentication Required</p> // Display Login Form
      }
    }

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

What is preventing me from renaming a file in PHP when passed through jQuery?

Hello to all users! I've encountered an issue where I can't seem to change the file name in PHP that is being passed from jQuery: Here is the JavaScript code where I pass the file to the PHP handler: var url = '/temp.php'; var xhr = ...

The combination of useSWR with graphql-request appears to trigger a continuous loop of requests being sent, even

Creating a custom hook to retrieve a list of bookings using the argument search, which represents the booking status and defaults to 'NEW'. This hook can be utilized with different values for search to fetch bookings based on their status. The i ...

Troubleshooting ASP.NET Ajax Error Code 0

Starting from scratch with asp.net and hoping to incorporate infinite scrolling using jQuery Ajax and ASP.NET MVC. Here's the progress so far: <div id="container"></div> <div id="progress" style="display:none"> <h4>Loading ...

Guide to accessing child prop reference in Vue 3 using Element Plus UI library

I am encountering an issue with a dropdown component labeled 'dropdown' When selecting an item, I need to retrieve the selected label (not just the value) Currently, when using dropdown.value, I receive an object containing a key and its corres ...

Guide on properly defining typed props in Next.js using TypeScript

Just diving into my first typescript project and finding myself in need of some basic assistance... My code seems to be running smoothly using npm run dev, but I encountered an error when trying to use npm run build. Error: Binding element 'allImageD ...

Encountering an issue with the Bootstrap modal popup not functioning properly within a JSP file, implemented alongside the Apache Tiles framework

In my Spring Boot web application, I have incorporated Bootstrap with features like SB Admin and data tables, all of which are functioning correctly. However, I am facing an issue with implementing a Bootstrap modal popup. Below is my JSP code: <%@ ...

Ways to identify when a specific react component has been clicked

Currently working on developing a klondike game with 4 empty stacks at the start of the game. The initial page layout resembles the first image provided in the link. I am facing an issue where I cannot determine which component was clicked when clicking on ...

What exactly does form.getHeaders(); mean?

Attempting to streamline the upload process, I have come up with the following code: var http = require('http'); var request = http.request({ method: 'post', host: 'https://www.ws-ti.4bank.com', path: '/img/create ...

How to retrieve a single user using server-side props in Next.js

I'm currently building a dashboard using nextjs and implementing authentication with next-auth. However, I've encountered an issue when trying to display individual user data upon login to the dashboard. It seems that I am unable to retrieve the ...

Utilizing Server-Sent Events to display a interactive navigation button

Currently, I am managing a web-based point of sale system where some buttons are hidden for specific functions. To streamline the process, I would like to allow managers to simply click on an "Enable" button in the admin panel and have it immediately refle ...

Is it possible that .focus() does not function on a duplicated object?

Greetings to all! I have created a form with rows of input text fields. Users can add as many rows as needed by clicking the 'add row' button. The functionality to clone() for adding rows is working perfectly. In each row, an input field can o ...

Production environment causing VueJs components to not update their style accordingly

Recently, I deployed a Vue app that was integrated with Laravel on a shared hosting platform. However, I encountered an issue after updating a component's style and running the production command again. Despite redeploying and updating the "public/app ...

Tips for importing a JavaScript file from a URL and initializing a class in a React component

I am looking to incorporate the PitchPrint app into a React website. They offer a tutorial for vanilla HTML/JS integration here. Following their instructions, I included script tags with links to jQuery and their app file in my index.html file. I then crea ...

What are the best practices for implementing Laravel and Vue together?

Hello, I'm currently new to working with Laravel and Vue. I have successfully registered a component, but it's not displaying the content in my blade template. I would greatly appreciate any help or guidance on properly implementing this in Larav ...

Converting HTML/Javascript codes for Android Application use in Eclipse: A Step-by-Step Guide

How can I implement this in Java? Here is the HTML: <head> <title>Google Maps JavaScript API v3 Example: Geocoding Simple</title> <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="styles ...

Optimally displaying extensive lists on a webpage using HTML

Are there any advanced javascript libraries that can efficiently handle loading a large list by only loading the visible part and simulating the scrollbar? <div id='container'> <!-- Empty space to mimic scrollbar, but preloading conte ...

Getting a 401 error when using the Companies House API with jQuery and ajax

I attempted to retrieve JSON data from the UK Companies House API but encountered a 401 error An error occurred: the server responded with a status of 401 (Unauthorized) I implemented jQuery with the ajax() method for this task, and here is a snippet o ...

Sorting elements to the beginning of each nested array

Looking to rearrange the elements in the given nested array, moving the element with the id 'cat_spc_my_special_id' to the top of the list using the keyword 'special'. There are 4 items currently in the above array, and the goal is to ...

Display a single submenu on mouseover using Javascript

Hello there, I have been working on creating a small menu using only Javascript, but I am facing an issue where the onmouseover event is displaying all submenus instead of just one. Below is the section of code that is supposed to change style.display to ...

AngularJS JQ Widgets Chart Display Issue

Trying to incorporate a chart using JQ widget, the code snippet below shows my controller code. When making an ajax call to retrieve data from the server, the response is received but the chart displays the previous data of that variable as undefined. Hard ...