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

Backend communication functions seamlessly within the service scope, yet encounters obstacles beyond the service boundaries

I'm facing an issue with accessing data from my backend. Although the service successfully retrieves and logs the data, when I try to use that service in a different module, it either shows "undefined" or "Observable". Does anyone have any suggestions ...

What is the best way to test the validity of a form while also verifying email availability?

I am currently working on implementing async validation in reactive forms. My goal is to disable the submit button whenever a new input is provided. However, I am facing an issue where if duplicate emails are entered, the form remains valid for a brief per ...

The absence of the 'profileStore' property is noticed in the '{}' type, which is necessary in the 'Readonly<AppProps>' type according to TypeScript error code ts(2741)

I'm currently using MobX React with TypeScript Why am I getting an error with <MainNote/>? Do I just need to set default props? https://i.stack.imgur.com/5L5bq.png The error message states: Property 'profileStore' is missing in typ ...

When attempting to create a JavaScript class within a NextJS library that utilizes server-side code, an error is encountered on the frontend despite not

Currently, I am in the process of developing a NextJS project and working on constructing a library that can be utilized in future projects. As part of this library, I have created a JavaScript class detailed below: export class EmailManager { private ...

What is the process for overriding the module declaration for `*.svg` in Next.js?

The recent modification in Next.js (v11.0.x) has introduced new type definitions: For next-env.d.ts (regenerated at every build and not modifiable): /// <reference types="next" /> /// <reference types="next/types/global" /> ...

The isMobile variable from useSettings is failing to update correctly when the window is resized in a Next

I’ve encountered an issue with determining the device type (mobile, tablet, or desktop) in my Next.js application. I’ve utilized the is-mobile npm package to identify the device type and passing this data through settings. However, the isMobile flag fa ...

How can I limit a type parameter to only be a specific subset of another type in TypeScript?

In my app, I define a type that includes all the services available, as shown below: type Services = { service0: () => string; service1: () => string; } Now, I want to create a function that can accept a type which is a subset of the Service ...

What is the process for defining the root of a project in ESLint?

I've been working on a project using Next.js and Typescript. My imports look like this: import Component from "/components/Component/Component";, with the root directory being specified as /src. This setup works fine in Next.js, but ESLint k ...

Having trouble importing the Renderer2 component in Angular

Trying to include Renderer2 with the following import: import { Renderer2 } from '@angular/core'; Encountering an error: "Module 'project/node_modules/@angular/core/index' does not have an exported member 'Renderer2'. Puzz ...

What is the abbreviation for indicating a return type as nullable?

Is there a way to use shorthand for nullable return types in TypeScript similar to using "name?: type" for parameters? function veryUsefulFunction(val?: string /* this is OK */) // but not this or other things I've tried. // is there a way a ...

What strategies can be implemented to maximize the efficiency of Firebase when designing an admin-only page, in order to minimize unnecessary data reads and

Currently, I have established a secure page within our website that is exclusively accessible to administrators. The technology stack being used includes React Next.js and Cloud Firestore for managing data. As the page is loaded, a read operation in Firest ...

Uh-oh! You can't configure Next.js using 'next.config.ts'. You'll need to switch it out for 'next.config.js'

I've encountered an issue while working on my TypeScript project with Next.js. Initially, I named my config file as next.config.js, but it resulted in a warning in the tsconfig.json file stating "next.config.ts not found," leading to a warning sign on ...

Error in TypeScript: Gulp + Browserify combination is not yielding the expected type

I keep encountering an error whenever I try to run this script. The error message I receive is: -> % gulp compile-js [22:18:57] Using gulpfile ~/wwwdata/projects/site/gulpfile.js [22:18:57] Starting 'compile-js'... events.js:141 th ...

Template literal types in TypeScript and Visual Studio Code: An unbeatable duo

I'm encountering an issue while attempting to utilize literal types in Visual Studio Code. When following the example from the documentation, https://i.stack.imgur.com/V6njl.png eslint is flagging an error in the code (Parsing error: Type expected.e ...

Utilizing solidity event emitters within a react useEffect hook

I am trying to subscribe to a solidity event listener using useEffect, but it seems to be called twice during render. How can I properly unsubscribe from the events or handle this issue? useEffect(() => { console.log('ADD'); counterContra ...

Converting a string to an HTML object in Angular using Typescript and assigning it to a variable

I am facing an issue with passing HTML content from a service to a div element. I have a function that fetches HTML content as a string from a file and converts it into an HTML object, which I can see working in the console. However, when trying to assign ...

"Directly following the index page, set up a dynamic route using

When using Next.js, it is common to create dynamic routes with file structures like: pages/products/[id].js, which would result in www.website.com/products/productId2323 My goal is to include a "workspace" identifier in my route so that after a user logs ...

`Why TypeScript in React may throw an error when using a setter`

As I work on building a small todo app in TypeScript with React, I encountered an issue when attempting to add a new todo item to my list. It seems like the problem may lie in how I am using the setter function and that I need to incorporate Dispatch and s ...

Retrieve the thousand separator for numbers using Angular in various languages

When using the English locale, numbers appear as follows: 111,111,222.00, with a comma as the thousand separator and a point as the decimal separator. In languages like German, the same number would be represented as 111.111.222,00, reversing the positions ...

Extension for VSCode: Retrieve previous and current versions of a file

My current project involves creating a VSCode extension that needs to access the current open file and the same file from the previous git revision/commit. This is essentially what happens when you click the open changes button in vscode. https://i.stack. ...