Adding next-auth middleware on top of nextjs middleware in Nextjs implementation

I am in need of the nextjs middleware to be activated for two distinct paths:

  • Firstly, to serve as a protection against unauthorized access by utilizing next-auth.
  • Secondly, to redirect authorized users from specific pages. For example, if an authorized user lands on any page within the auth namespace, then they should be redirected to the dashboard. (Although I can achieve this on the client side, I find it more streamlined at the middleware level).

The issue is that it seems like next-auth takes control of the entire middleware logic:


import { withAuth } from "next-auth/middleware"

export default withAuth(
  function middleware(req) {
    console.log(req.nextauth.token)
  },
  {
    callbacks: {
      authorized: ({ token }) => token?.role === "admin",
    },
  }
)

export const config = { matcher: ["/dashboard/:path*", "/auth/:path*"] };

Is there a way to transfer this logic to a standard nextjs middleware? If not, how can I implement unrelated logic alongside next-auth?

Email: [email protected]

Answer №1

When working with middleware in expressjs, consider utilizing the next-connect package, available here.

This approach mirrors how we implement middleware in express js, but it keeps nextjs on each specific route instead of defining a general middleware and path.

For instance, in the following sample route, you can observe that certain validations are applied exclusively to this particular route, not globally across the entire project.

import nc from 'next-connect'
import { validateToken, someBodyValidation, handleError } from './middlewares'

const handler = nc({ onError: handleError })

handler.use(validateToken)

handler.get(async (req: INextApiRequest, res: NextApiResponse) => {})

handler.post(someBodyValidation, async (req: INextApiRequest, res: NextApiResponse) => {})

The line handler.use(validateUserToken) applies to all routes within this section (both get and post apis). Additionally, notice the extra middleware specified in the .post method - this is for validating request body specifically for that individual post route. This segregation allows for better organization and control over middleware functions.

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

Executing a search within the current connection in Node.js

In the code snippet provided, the need is to execute the second SQL query (query2) after constructing it based on the results of the first query (query1). However, even though the second query is successfully built, it is not being executed. Assistance i ...

position blocks next to each other within a container

Thank you for all the hard work! I've been struggling to figure out how to align blocks next to each other within a div. It may not be that difficult, but I just can't seem to find an elegant solution... Here is the HTML code snippet: <div ...

Securely submit user information using NextJs with Supabase's authentication feature

I've been attempting to post an article by inserting the user.id into the "posts table (id column)" but I'm having trouble getting it to work! Here is my current code snippet. "use client"; import { useState } from "react"; i ...

What is the reason that preventDefault fails but return false succeeds in stopping the default behavior

I'm having trouble with my preventDefault code not working as expected. While using return false seems to work fine, I've heard that it's not the best practice. Any ideas why this might be happening? if ($('.signup').length == 0) ...

Sending data from a dynamically created PHP table to a modal

In my PHP-generated table, I have: <tbody> <?php $results = DB::select()->from('users')->execute(); foreach ($results as $user) { echo "<tr id='".$user['id']."'> <input type=&bs ...

Is it feasible to send props to { children } within a React functional component?

Workaround presented below. I am attempting to send props down to a child component using {children}. The Parent component: const ParentComp = ({ children, propsToSendToChild }) => ( <div>Dynamic component content: {children} &l ...

The ScriptManager.RegisterStartupScript function does not execute a second time when used inside an UpdatePanel

My aspx page <span> <asp:UpdatePanel ID="upPlayBtn" runat="server" > <ContentTemplate> <asp:Button runat="server" id="btn" Text="Play" OnClick="btnPlay" /> </ContentTemplate> </asp:UpdatePanel> </span> ...

showing a fading-in effect after a successful AJAX post

Maybe a simple question, but I've been struggling to make this work for quite some time now. Despite trying various solutions from stackoverflow, I can't seem to get it right. Perhaps fresh eyes could help me figure out how to achieve this. My g ...

Using axios to pass parameters in a URL with the GET method on a localhost server

I need help using Axios to consume my Go lang API in my React front-end. The route for the API is localhost:1323/profile/email/:email/password/:password, but I'm struggling to figure out how to pass the email and password parameters in the Axios GET r ...

How to stop a component template in Angular from displaying both conditional statements simultaneously?

I want to prevent my component template from briefly displaying both conditional statements when the condition changes after the component has been initialized. My application receives a token, and depending on its validity, it shows the appropriate conte ...

Looking to sanitize an array of objects in Node.js? If you find that manually iterating through it only returns 'object Object', there are alternative methods to properly

I have a collection of items structured like this: var data = [ { msg: 'text' }, { src: 'pic.jpg',id: 21,title: 'ABC' } ]; My goal is to cleanse the values by manually iterating throug ...

Creating tables using ng-repeat in AngularJS and Bootstrap

Although I am new to Angular, I have been struggling with a problem for the past few days and can't seem to find a solution. I want to create a matrix of images (charts generated by angular-chart module) with 2 columns that will dynamically load a va ...

Guide on organizing users into groups and filtering them using Firestore's reference field type

I currently manage a small group of employees with plans to expand in the future. To streamline operations, I am looking to implement a grouping feature that allows users to sort employees based on their assigned groups. Although I thought about using the ...

React Express Error: Unable to access property 'then' of undefined

I'm facing an issue while trying to server-side render my react app for users who have disabled JavaScript and also for better search engine optimization. However, I am encountering the following error: TypeError: Cannot read property 'then' ...

Combining four numbers to calculate a total with the click of a button

I am currently attempting to calculate the sum of 4 entries in 4 separate text fields, and everything appears to be working correctly except that when I click the button, the sum is not being set. For example, if I enter the number 1 in each text input, th ...

Having trouble with NextJs router 404 error when refreshing the page on Digital Ocean?

I am currently working with a NextJs project that has been exported as a static site and is being hosted on Digital Ocean's App platform. I am using next/router to handle routing within the application. One issue that I have encountered is when attem ...

Transfer photos and videos to an external server using Javascript with Meteor framework

I currently have a meteor application hosted on Digital Ocean. I am considering setting up a dedicated server to store all images and videos separately from the site itself. Whenever a user uploads new media, it will be saved to this separate server. Does ...

"Invalid operation" error encountered within a Flask function in Python

I am trying to store a 'person' resource in a .ttl file using a JavaScript function: Here is my SPARQL query: @app.route('/registraAnnotatore/<author>+<mail>', methods=['POST']) def registraAnnotatore(author, ...

Highcharts introduces shared tooltips for specific data series

I am seeking to implement specific behavior in highcharts regarding tooltips. The desired setup includes having two types of tooltips: the default shared tooltip a custom tooltip For the custom tooltip, a simple formatter can be utilized. However, the c ...

Hotjar is experiencing difficulties in gathering data because of a CSP (Content Security Policy) issue

As I attempt to integrate hotjar into my nextjs project, I keep encountering an error in the console: The browser refuses to connect to 'wss://ws.hotjar.com/api/v2/client/ws?v=5' due to a violation of the Content Security Policy directive. The e ...