Should I specify each protected route in the middleware file in the matcher for NextJs 14?

Below is the middleware file I've implemented:

import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
import { getApiAuth } from "./app/middleware/api/auth";

const validateApi = (req: Request) => {
    const isValid = getApiAuth(req);

    if (!isValid)
        return new NextResponse(
            JSON.stringify({
                message: "Un-authorized",
            }),
            {
                status: 401,
            }
        );
};

// To make this function asynchronous, mark it as `async` when using `await`
export function middleware(request: NextRequest) {
    console.log("Cookie", request.cookies);
    const isApiPath = request.nextUrl.pathname.startsWith("/api");

    if (isApiPath) {
        return validateApi(request);
    }

    return NextResponse.next();
}


export const config = {
    matcher: "/((?!api/login|_next/static|_next/image|favicon.ico).*)",
};

I am looking for a way to dynamically generate the matcher regex in JavaScript or find a more concise method to protect routes. My goal is to configure the matcher variable with minimal code to secure routes and specify public routes.


// Matcher example: '/((?!api|_next/static|_next/image|favicon.ico).*)'

const publicRoutes = [
    "api/login",
    "_next/static",
    "_next/image",
    "favicon.ico",
];

export const config = {
    matcher: `/((?!${publicRoutes.join("|")}).*)`,
};

Answer №1

I have the ability to create an array of accessible routes and compare them with the requested route in the middleware

export const publicAppRoutes = ["/login", "/getting-started", "/reset-password"]

export const checkAuthForAppRoute = async (request: NextRequest, token: JWT | null) => {
const url = new URL(request.url);
const path = url?.pathname

const isPublicPath = publicAppRoutes.find(p => path.startsWith(p))

if (isPublicPath) {
    console.log("FOUND PUBLIC APP ROUTE PATH (skipping authorization check)")
    return true
}

if (!token) return false

if (!token?.user) return false

return true
}

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

Support for Vue 3.4 same-name shorthand has been added to VS Code

After upgrading my Vue 3 project to version 3.4, I encountered an issue with vs-code highlighting same-name shorthand as an error, even though it was functioning correctly in my code. I am using the volar extension. Is there a way to resolve this so that v ...

render target in three.js EffectComposer

When we utilize an EffectComposer, the scene is rendered into either composer.renderTarget2 or composer.renderTarget1. In a particular example, I came across this: renderer.render( scene, camera, composer.renderTarget2, true ); renderer.shadowMapEnabled ...

Utilizing middleware with express in the proper manner

Hello there! I'm just double-checking to see if I am using the correct method for implementing middleware in my simple express app. Specifically, I am trying to ensure that the email entered during registration is unique. Here's an example of wha ...

Importing JS files or SDKs in Angular that are not modules

Currently, I am incorporating the Avaya SDK (which consists of 3 JS files) into my Angular project. However, when attempting to import it, I encounter an error stating that it is not recognized as a module. Any suggestions on how to resolve this issue? Th ...

The JSON response may be null, yet the data flows seamlessly to the success function in

Currently, I am facing an issue with Ajax. The situation is as follows: I want to check if a user is available by typing their email address. Therefore, I have created a JavaScript function that includes an Ajax script for this purpose. Here is my code: $ ...

Issue: Unable to 'locate' or 'access' ./lib/React folder while utilizing webpack

I've been delving into the world of React for a while now and decided to experiment with integrating it with webpack. Below is my webpack.config.js : var path = require('path'); module.exports = { entry: './app.js', outp ...

How can you use JavaScript to assign a data value to a hyperlink?

I'm currently facing an issue with assigning a value to the data-attribute of an anchor tag. Below is the code snippet in question: <script> window.onload = function(){ document.getElementById("setcolor").click(); } var color = "red"; document ...

Obtain asynchronous result from updating state in React

I am trying to achieve the following: myFunction = () => { this.setState( state => { const originalBar = state.bar; return { foo: "bar" }; }, () => ({ originalBar, newBar: state.foo }) //return this object ...

When an object is created, what is the most effective way to manage the asynchronous setup of one of its properties?

This is my first attempt at creating a JavaScript module/library, so I'm feeling a bit out of my depth. I apologize for not knowing exactly what to search for. My goal is to develop a library that stores information from a user-provided URL. The func ...

Is there a way to specifically remove only the last row from a table?

Recently, I encountered a problem with my JS code that adds and removes table rows based on user interaction. Adding rows functioned perfectly, but the issue arose when attempting to delete rows. Instead of deleting only the last row as intended, all rows ...

Adjust the image dimensions within the DIV container

I am currently working on creating my personal portfolio website. I have encountered an issue where the image inside a div element enlarges the size of the entire div as well. My goal is to keep the image slightly larger while maintaining the same size for ...

Interacting with objects in a loaded OBJ model using ThreeJS

I have an obj model representing a map with tree objects. After successfully loading the model, I am trying to access one specific tree object named Tree1. How can I achieve this? Currently, my code looks like this: loader.load( 'map.obj', fun ...

Animating with React using the animationDelay style does not produce the desired effect

Is there a way to apply an animation to each letter in a word individually when hovering over the word? I want the animation to affect each letter with an increasing delay, rather than all at once. For example, if scaling each letter by 1.1 is the animatio ...

Exploring Database with NodeJS, Express, and HTML

My goal is to create a basic web application using node.js where users can input data into a search bar and have that input sent to the server for database query. While I've successfully set up and connected my database, here's a glimpse of my co ...

The bundle.js file is displaying HTML code instead of JavaScript

I have been working on setting up redux server-side rendering using express.js. Most of the setup is done, but I encountered an error while trying to render the page in the browser. The error message Uncaught SyntaxError: Unexpected token < is appearin ...

Acquiring HTML form data using JavaScript

Although it may seem trivial, I'm facing a challenge. I have an HTML form that is dynamically generated by JavaScript and populated with initial data fetched from the server. The form is displayed correctly with the pre-filled data. My goal is to allo ...

No results are being returned by karma.js after setting up a basic "karma init" configuration

Currently, I am working through the tutorial "Introduction to Karma" on egghead.io which can be found here. To set up Karma on Windows, I followed these steps: > npm install --g karma-cli > npm install karma karma-jasmine karma-chrome-launcher --sav ...

The cURL command successfully executes the request, however, it fails to work in both Postman and web browsers

A problem arises when the Node Js (express) server responds to requests using cUrl, resulting in an infinite load. However, when requested via Postman or a browser, there are no errors but still faces issues. Despite searching for solutions, none of the s ...

The execution of the function halts as soon as the player emerges victorious

In my attempt to create a basic game where players compete to click their designated button faster to reach 100%, I am in need of assistance with implementing a logic that determines the winner once one player reaches or exceeds 100. Essentially, I want ...

Angular.js has encountered an error due to exceeding the maximum call stack size

Hello everyone! I attempted to create recursion in order to extend my $routeProvider in Angular.js with the following code: var pages = { 'home': { 'url': '/', 'partialName': 'index', ...