Next.JS-13 has encountered an inappropriate middleware in its App Based Routing functionality

I am currently working on developing a user authentication system that includes features for Login, Signup, and Logout. As part of this project, I have created a middleware.ts file in the src directory, which is located next to the app directory. Below is the content of my middleware.ts file along with its path: (path: src/middleware.ts)

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

export function middleware(request: NextRequest)
{
    const path = request.nextUrl.pathname;

    const isPublicPath = path.includes('/login') || path.includes('/signup');

    const token = request.cookies.get('token')?.value || '';

    if(isPublicPath && token)
    {
        return NextResponse.redirect(new URL('/', request.nextUrl));
    }

    if(!isPublicPath && !token)
    {
        return NextResponse.redirect(new URL('/login', request.nextUrl));
    }
}

export const config = {
    matcher:[
        '/',
        '/profile',
        '/login',
        'signup',
    ],
}

Upon starting the server, I encountered the following errors:

source does not start with / for route {"source":"signup"}

Subsequently, another error occurred:

Invalid middleware found.

Despite attempting to resolve these issues by saving all changes and restarting the server, the problems persisted. Similar connectivity issues had arisen previously, but after making some adjustments, the server eventually connected successfully.

Answer №1

There appears to be a mistake in the matcher array within the configuration.

The correct value should be '/signup' instead of 'signup'.

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

Ways to attach an event listener to a useRef hook within a useEffect hook

As I work on creating a custom hook, I am faced with the task of adding an event listener to a ref. However, I am uncertain about how to properly handle cleaning up the event listener since both listRef and listRef.current may potentially be null: const ...

What steps need to be taken in VSCode to import React using IntelliSense?

When I press Enter in that image, nothing seems to occur. I believed IntelliSense would automatically insert import React from 'react'; at the beginning of the file. https://i.stack.imgur.com/7HxAf.png ...

Upon completion of a promise in an express middleware and breaking out of a loop, a 404 error is returned

In my efforts to retrieve an array of object (car) from express using database functions in conjunction with the stolenCarDb object, everything seems to be working fine. However, when attempting the following code snippet, it results in a 404 error w ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

Failure of Styling Inheritance in Angular 2 Child Components from Parent Components

My Parent Component utilizes a Child Component. I have defined the necessary styles in the Parent CSS file, and these styles change appropriately when hovering over the div. However, the Child Component does not inherit the styling classes of the Parent Co ...

Setting up TypeScript to function with Webpack's resolve.modules

Imagine having a webpack configuration that looks like this: resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'], modules: ['my_modules', 'node_modules'], }, You have a ...

The mongodb server suddenly crashes following a notification that the serverStatus was experiencing significant delays

My EC2 instance is running a mongodb service that consistently crashes after some time. Upon checking the status of the mongodb service with systemctl status mongodb, I received the following output: ● mongodb.service - High-performance, schema-free doc ...

Enrich your TypeScript code by unleashing the power of enum typing in overloading logical

I have a custom enum called PathDirection that represents different directions export enum PathDirection { LEFT="LEFT"; RIGHT="RIGHT"; }; Within my code, I need to toggle between the two directions. For example: let currentDire ...

Is it possible for me to create an interface that enables me to invoke a custom method on particular strings?

My database returns objects structured like this: interface Bicycle { id: string; created_at: string; } The data in the created_at field is a machine-friendly date that I need to convert into a Date object for localization: new Date(bike.created_at). ...

how to implement dynamic water fill effects using SVG in an Angular application

Take a look at the code snippet here HTML TypeScript data = [ { name: 'server1', humidity: '50.9' }, { name: 'server2', humidity: '52.9', }, { name: 'server3', humidity: ...

Issue with error handling in Node and MongoDB when using Express, Mongoose, and the 'mongoose-unique-validator' plugin

I am facing an issue with the 'mongoose-unique-validator' plugin when trying to handle Mongo ValidationError in my custom error handler. Despite other errors being handled correctly, this specific one is not triggering the desired response from m ...

What is the most effective way in MongoDB to insert data only if it does not already exist in the database?

Is there an optimal way to insert data into MongoDB only if it doesn't already exist in the table? The unique field for searching is hash, which is also indexed. router.post('/', async (req, res) => { try{ var id = null const ...

Using Typescript: What is the best way to convert a variable into a specific element of an array?

List of Strings: const myStrings = ["one", "two", "three"]; const newString = "two"; The variable newString is currently just a string, but I would like its type to be an element of myStrings. Is there a way to achi ...

Transform a row in an ng Smart table to a routerlink using Angular 2

I've been exploring ng2 Smart Table and I'm looking to convert a row (or even cell data) into a clickable link using routerlink. The current method I'm employing to retrieve some of my row's data is as follows: onUserRowSelect(event) ...

Executing a MongoDB query can only be successful by utilizing the copy and paste method

Recently, I encountered an unusual issue with MongoDB while attempting to query the database. Specifically, when running a query like db.departments.find({"key": "MEL 301"}), it returned no results. The MongoDB database is hosted on mLab, allowing me to v ...

Creating custom observables by utilizing ViewChildren event and void functions in Angular 12: A step-by-step guide

I am currently working on developing a typeahead feature that triggers a service call on keyup event as the user types in an input field. The challenge I face is that my input field is enclosed within an *ngIf block, which requires me to utilize ViewChildr ...

Is it possible to conditionally trigger useLazyQuery in RTK Query?

Is it possible to obtain trigger from useLazyQuery conditionally? const [trigger] = props.useLazySearchQuery(); My objective is to retrieve trigger only when useLazySearchQuery is provided in the props. One way I can achieve this is by using const [ ...

Utilizing Typescript for parsing large JSON files

I have encountered an issue while trying to parse/process a large 25 MB JSON file using Typescript. It seems that the code I have written is taking too long (and sometimes even timing out). I am not sure why this is happening or if there is a more efficien ...

Create a line break in the React Mui DataGrid to ensure that when the text inside a row reaches its maximum

I'm facing an issue with a table created using MUI DataGrid. When user input is too long, the text gets truncated with "..." at the end. My goal is to have the text break into multiple lines within the column, similar to this example: I want the text ...

How to apply a single pipe to filter columns in Angular 2 with an array of values

I need to sort through an array of objects using multiple array string values. Here is an example of how my array of objects looks like: [{ "name": "FULLY MAINTAINED MARUTI SUZUKI SWIFT VDI 2008", "model": "Swift" }, { "name": "maruti suzuki ...