Protecting website pages on both the admin and user side in Next.js 14 to ensure maximum security

I'm currently using nextjs 14 and I am working on developing a website similar to a property app. It will have an admin dashboard and a user side. How can I ensure the security of both the admin and user sides, and what should my folder structure look like?

I know that middleware can be used for this purpose, but I need detailed guidance on how to implement it.

I have attempted having two layouts - one for authentication, one for the dashboard, and one for the user side. My goal is to restrict access so that when a user is logged in, they can only see pages related to the user side. Similarly, when an admin is logged in, they should have access to all admin dashboard pages.

If no one is logged in, the user should be redirected straight to the login page without being able to access any other pages. Unfortunately, I am facing challenges implementing this functionality.

Answer №1

If you're unfamiliar with how authentication and authorization function in Next.js, I recommend checking out the dashboard app for detailed insights. The adding authentication section provides specific guidance on this topic.

If you're struggling to grasp the concept, I've outlined some basics below to help you understand how to achieve your desired outcome,

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  
  // Assuming you have a function to verify the user's role
  const userRole = getUserRole(request);

  // Define routes that require admin access
  const adminRoutes = ['/admin/dashboard', '/admin/settings'];
  // Define routes that require user access
  const userRoutes = ['/user/profile', '/user/settings'];

  // Redirect to login if not authenticated
  if (!userRole && pathname.startsWith('/admin/') || pathname.startsWith('/user/')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  // Redirect if user does not have admin access
  if (userRole !== 'admin' && adminRoutes.includes(pathname)) {
    return NextResponse.redirect(new URL('/', request.url));
  }

  // Redirect if user does not have user access
  if (userRole !== 'user' && userRoutes.includes(pathname)) {
    return NextResponse.redirect(new URL('/', request.url));
  }

  return NextResponse.next();
}

// Mock function to get user role from the request
function getUserRole(request: NextRequest): string | null {
  // Implement your logic to retrieve user role from cookies, JWT, etc.
  return null; // Placeholder return
}

You can explore examples of Role-Based Authorization or Role-Based Access Control for more information and implementation ideas.

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

Guide for implementing onclick event for info boxes in push pins on Bing Maps using ReactJS

I have successfully placed all the coordinates on the map using pushpins, but now I want to create an event that shows an infobox when a pushpin is clicked. Could someone provide an example of how to hide infoboxes and only show them when a pushpin is cli ...

Enhance the Header component by incorporating a logout button that seamlessly navigates with the NextJS App

Currently, I am utilizing NextJS 14 with App router alongside Spring Boot on the backend. Within my application, I have both public and private routes set up. For the private routes, users are required to log in through a designated login page. Upon succes ...

Clearing hoverIntent using jQuery

In my scenario, I have three items identified as X, Y, and Z. The functionality of hovering is controlled by the hoverIntent. When I hover on item X, a tooltip is displayed using the following code: jQuery('.tooltiper').hoverIntent({ ove ...

Verify if the connection to MongoDB Atlas has been established for MongoDB

When working with MongoDB, I find myself switching between a local database during development and MongoDB Atlas in production. My goal is to implement an efficient text search method that utilizes $search when connected to MongoDB Atlas, and $text when co ...

If the href attribute is set to "#" or the target attribute is set to "_blank", then the <a> request cannot be prevented

I have a registration site that triggers a warning window whenever a user clicks on any link during the registration process. However, I want to exclude <a> tags with href="#" and target="_blank" attributes from this behavior. Essentially, I want to ...

Sending a reference to the event object within a JavaScript function

There are times when we need to use the event object in JavaScript. Below is an example of how we can pass the event: function test(e){ console.log(e); e.preventDefault(); console.log("You are not going to redirect"); } HTML <a href="www. ...

With Ionic, you can use one single codebase for both iPad and iPhone

I currently have a complete app developed using ionic and angularjs that is functioning well on iPads and Android devices. Now we are looking to launch it for iPhones and Android smartphones with some design modifications. Is there a method to achieve th ...

Unable to connect Dropzone to dynamically loaded DIV using AJAX

Using Dropzone for client-side image uploads has been a breeze. Take a look at this basic example that is currently up and running: If you examine the source code, you'll notice that I am utilizing JQuery to connect Dropzone to the upload1 div ID. H ...

What is the best way to achieve line breaks in text that auto-wraps in JavaScript/PHP?

My resizable div contains text/sentences. As I adjust the size of the div, the text wraps itself to perfectly fit within the available space in the container div. Now, I am faced with the task of converting this dynamic text into an image using php and th ...

The API successfully completed its operation without issuing a response while attempting to retrieve information from a different page

I've implemented an endpoint that connects to an external database and a page that calls this endpoint within the getServerSideProps function. When I check the API endpoint, it successfully returns data. However, when I navigate to the page, I encount ...

When using `require('backbone')`, the returned object can vary depending on the file it is called in

backbone1.js var backbone1=require('backbone'); window.backbone=backbone1; backbone2.js console.log(window.backbone===require('backbone')); Why is the condition returning false. Shouldn't it return the same object everytime? E ...

The version of caniuse-lite in Browserslist is no longer current. To update, please execute the following command: `y

I am encountering an error message in 2 of my Next.js applications that says: Browserslist: caniuse-lite is outdated. Please run next command 'yarn upgrade'. This message appears when I execute commands like yarn dev, yarn start, or yarn build. T ...

Retrieving data from a remote source repeatedly based on user selections on a single page

In my current project, I am utilizing next js to build a web application. One of the pages in this app has the following structure: <page> <component_1> This component fetches data from a remote server using `getInitialProps` (alternat ...

Where is the appropriate location to incorporate Vue.config.devtools = true?

I am interested in utilizing the Vue.js devtools, but I am uncertain about how to enable them. It seems like I need to include Vue.config.devtools = true after Vue has been loaded. However, it appears that Vue is loaded within a minified index.html file l ...

What is preventing obj from being iterable?

When I try to compile this code, an error appears stating that the object is not iterable. Why is this happening? My goal is to determine the number of users currently online. let users = { Alan: { age: 27, online: false }, Jeff: { age ...

What is the best method to create random coordinates that fall outside of the circle located within a rectangular area?

Suppose the following scenario: A rectangular area with dimensions length l and breadth b A circle with a radius r The circle is positioned inside the rectangular area as depicted in the image below Check out the image here - Red areas show expected even ...

How can we efficiently generate ReactJS Router for Links and seamlessly display a unique page for each Link?

Currently, I have an array of objects named titleUrl, which contains titles and URLs retrieved from an API. To display these as links on the sidebar, I am utilizing a custom component called MenuLink. The links are generated by iterating over the keys in t ...

Tips for managing and identifying canceled requests in an Angular HTTP interceptor

Having trouble handling cancelled requests in my http interceptor. Despite trying various methods from SO, I can't seem to catch it. Here is an example of how my interceptor looks: public intercept(req: HttpRequest<any>, next: HttpHandler) { ...

The media parameter seems to be malfunctioning when attempting to send it to the Kaleyra API using code

Attempting to send media through the Kaleyra API using my code is proving unsuccessful. However, when I make the same request via Postman, it works perfectly fine. async whatsappAPIWithAttachment(requestBody) { let api_key = ""; if (requ ...

How to clear a particular select option in react-bootstrap

I am looking for a solution to clear the second select when the first one selects option B. The clearing should involve removing the value, disabling it, and setting the default option to Select.... import React, { useState } from "react"; import ...