Is there a way to verify a user's authorization status within Next.js 12.1.6 middleware?

I'm implementing a Nextjs middleware to redirect unauthenticated users to the login page. It's currently working locally, but not on the remote server:

export async function middleware(req: NextRequest) {
    const { cookies } = req
    if (!cookies['next-auth.session-token.0']) {
        return NextResponse.rewrite(new URL('/login', req.url))
    }
    return NextResponse.next()
}
export const config = {
    matcher: ['/account/:path*'],
}

My setup includes Nextjs version 12.1.6 and next-auth version 4.10.0.

The .get() method mentioned in the Next docs for retrieving tokens from headers or cookies is not available in these versions.

The _middleware.ts file is located in a subfolder within the pages directory.

Answer №1

I have implemented this code snippet for user redirection in my project incorporating Next.js version 12.1 or above.

export async function middleware(req: NextRequest) {
    const currentUser = req.cookies.get("next-auth.session-token.0")?.value;

    if (!currentUser || (Date.now() > JSON.parse(currentUser).expiredAt)) {
        req.cookies.delete("currentUser");
        const response = NextResponse.redirect(new URL("/login", req.url));
        response.cookies.delete("currentUser");
        return response;
    }
    return NextResponse.next()
}

Answer №2

After updating to version 12.1.6, I was able to remotely and locally access the token in a new way:

const { cookies } = req
const authorized =
    cookies['__Secure-next-auth.session-token.0'] ||
    cookies['next-auth.session-token.0']

In version 12.1, the Middleware feature was still in Beta mode. It wasn't until version 12.2 that the stable version was released (check out nextjs.org/blog/next-12-2).

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

Exploring the various form types supported by 'react-hook-form'

I utilized react hooks form to create this form: import React from "react"; import ReactDOM from "react-dom"; import { useForm, SubmitHandler } from "react-hook-form"; import "./styles.css"; function App() { type ...

Failed to store item in localStorage

After successfully setting an object to localStorage, the value of the object stays null. I suspect that my use of async/await is causing this issue. I can confirm that I am correctly setting the state, as when I log the user in and navigate to the index ...

I am encountering an issue with the Link tag from next/link that is throwing an error. The error message states: "React.Children.only expected to receive a single React element

Hey everyone, I've come across an issue with using next/link in my code. Every time I replace the anchor tag with the "Link" tag, I encounter an error. I've searched for a solution but haven't found one yet. Any help would be greatly appreci ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

ESLint not functioning properly on TypeScript (.ts and .tsx) files within Visual Studio Code

After installing the ESLint extension in VSC, I encountered an issue where it was no longer working on the fly for my React project when I introduced Typescript. In the root of my project, I have a .eslintrc file with the following configuration: { "pa ...

``There is an issue with Cross-Origin Resource Sharing (CORS) in a Node.js application utilizing TypeScript

I've encountered some issues with my application, specifically regarding CORS. I suspect it may be due to a misconfiguration on my server. The problem arises when I attempt to create a user in my PostgreeSQL database via the frontend. I have a tsx com ...

Parsing JSON results in the return of two objects

I am analyzing a JSON file, expecting it to return Message[] using a promise. This code is similar to the one utilized in the Heroes sample project found in HTTP documentation { "data": [ {"id":"1","commid":"0","subject":"test1subject","body":" ...

Using references to pass variables in TypeScript [Angular 8]

I have several variables within the html of this component that are assigned their values by the typescript file. The declaration in the html is as follows: <h1>{{myproperty1}}<\h1> <h1>{{myproperty2}}<\h1> <h1>{{myp ...

Exploring how enums can be utilized to store categories in Angular applications

My application has enums for category names on both the back- and front-end: export enum CategoryEnum { All = 'All', Category1 = 'Category1', Category2 = 'Category2', Category3 = 'Category3', Cate ...

Issue encountered: Cannot locate module: Error message - Unable to find 'stream' in 'C:devjszip-test ode_modulesjsziplib' folder

I am encountering an issue in my angular 7 application while using jszip v3.2.1. During the project build process (e.g., running npm start), I receive the following error message: ERROR in ./node_modules/jszip/lib/readable-stream-browser.js Module not fo ...

Typescript: Enhance your coding experience with intelligent parameter suggestions for functions

Within a nest.js service, there is a service method that takes an error code and generates a corresponding message to display to the user. The example below shows a simplified version of this method: getGenericErrorMessage(input: string): string { co ...

Transferring a PDF document to Next.js

I am facing an issue while trying to upload a PDF file (CV) on next js. Everything seems fine according to my expectations, but when I console.log(req.data) it displays [object:object] Please note: When I console.log the data in frontend, it works fi ...

Angular 5 error handler does not support service calls

My HTTP calls are placed inside a service, as they should be. Within that service, I inject another service for handling error notifications. In an interesting turn of events, I noticed that when I place the notification call inside the catchError pipe, e ...

Guide on reading a request body in the next13 app router

the get route handler provided: export async function GET(request: Request) { // logs null console.log(request.body); return Response.json({ msg:'success' }) } despite including body data in the request, the logge ...

Unable to locate module: Unable to locate the file './Header.module.scss' in '/vercel/path0/components/Header'

I encountered an error while attempting to deploy my next application on Vercel. I have thoroughly reviewed my imports, but I am unable to pinpoint the issue. Module not found: Can't resolve './Header.module.scss' in '/vercel/path0/comp ...

The `_hex` property is undefined and cannot be read in Next.js while trying to buy NFTs

Currently, I am in the process of developing an NFT marketplace. Everything seems to be functioning properly when it comes to creating NFTs, but I have encountered an issue when attempting to purchase an NFT. The error message displayed is as follows: et ...

Monitor a universal function category

Trying to implement a TypeScript function that takes a single-argument function and returns a modified version of it with the argument wrapped in an object. However, struggling to keep track of the original function's generics: // ts v4.5.5 t ...

Is it possible for the getStaticPaths function to accept dynamic slugs?

Within a file named pages/posts/[...slugs].tsx, the getStaticPaths function is defined as follows: export async function getStaticPaths() { return { paths: [ { params: { slugs: ['1', 'hunt-for-the-hidden-reindeer'] } }, ...

What is the process for adding custom text to create a .d.ts file using the TypeScript compiler?

In my endeavor to develop a javascript module using TypeScript that is compatible with ES5 browsers and NodeJs modules, I have encountered a dilemma. I wish to avoid using import and export in TypeScrtipt as it creates dependencies on SystemJS, RequireJS, ...

The server side props in Next.js are not being loaded promptly

I am currently utilizing Supabase and facing an issue with loading the user session on the server side. When a page is refreshed, it recognizes that there is a user but not on the initial load (such as when coming from a magic link). How can I ensure that ...