Learn the process of transmitting data from middleware to components and APIs in Next.js version 13

I've been experimenting with the Next Js 13 middleware feature and I'm a bit confused about how to pass data from the middleware to components/pages/api.

For example, when trying to pass payload data or determine who the currently logged-in user is.

In the past, without using the middleware feature, I would create a middleware file and if jwt verification was successful, I would send/pass the payload data to my components/api like this:

import {example} from 'middleware/example'

const payload = await example(req, res)

However, with the Next Js 13 feature, after reading the docs, I only found examples of how to send responses like:

return new NextResponse(
  JSON.stringify({
    success: false,
    message: 'authentication failed'
  }),
  { status: 401, headers: { 'content-type': 'application/json' } }
)

If I use that method, it will return json data and not continue the middleware chain. If I try:

return NextResponse.next()

It will continue the middleware chain, but then how do I pass my payload data to components/pages/apis? I attempted something like this:

return NextResponse.next({tes: "test"})

But I couldn't figure out how to retrieve that data in my components/pages/api.

This is an excerpt from my middleware code:

if (request.nextUrl.pathname.startsWith('/api/posts')) {
        const requestHeaders = new Headers(request.headers)
        const authorization = requestHeaders.get('authorization')

        if (!authorization) {
            return new NextResponse(
                JSON.stringify({
                    success: false,
                    message: 'authentication failed'
                }),
                { status: 401, headers: { 'content-type': 'application/json' }
            )
        }

        const authSplit = authorization.split(' ')
        const [authType, authToken] = [
            authSplit[0],
            authSplit[1]
        ]

        if (authType !== 'Bearer') {
            return new NextResponse(
               JSON.stringify({
                    success: false,
                    message: 'authentication failed'
                }),
                { status: 401, headers: { 'content-type': 'application/json' } }
            )
        }

        const payload = await verify(authToken)

        if (!payload) {
            return new NextResponse(
                JSON.stringify({
                   success: false,
                    message: 'authentication failed'
                }),
                { status: 401, headers: { 'content-type': 'application/json' } }
            )
        }

        return NextResponse.next()
    }

Answer №1

Upon examining the code, I discovered a singular method involving request.header

middleware.ts:

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

// If `await` is utilized within, this function can be denoted as `async`
export function middleware(request: NextRequest) {
    console.log('middleware.ts, request.url:', request.url)

    const headers = new Headers(request.headers);
    headers.set('middlewareSet', 'mydata');

    const resp = NextResponse.next({
      request: {
        headers
      }
    });

    return resp;
}


// Refer to "Matching Paths" below for additional insights
export const config = {
    matcher: '/user/server',
}

/user/server/page.tsx

import { headers } from 'next/headers'

export default function Server() {
  const headersList = headers()
  const middlewareSet = headersList.get('middlewareSet')

  return (
    <div>
        <p>middlewareSet: {JSON.stringify(middlewareSet)}</p>        
        <p>headersList: {JSON.stringify(headersList)}</p>
    </div>
  )
}

The version of next.js being used is 13.4.1 and employs the app router.

Answer №2

I'm encountering a similar issue. There should be an easier method in Next.js server-side rendering for transferring variables from middleware to child components.

Perhaps a solution could look like this:

export async function customMiddleware(req: NextRequest) {
  const info = 'Greetings from the middleware!';
  req.someInfo = info;
  return NextResponse.next();
}

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

ESLint refuses to be turned off for a particular file

I am in the process of creating a Notes.ts file specifically for TypeScript notes. I require syntax highlighting but do not want to use eslint. How can I prevent eslint from running on my notes file? Directory Structure root/.eslintignore root/NestJS.ts r ...

Try block must be followed by either a catch block or a finally

Currently, I am utilizing Node, Express with EJS view engine, nano for CouchDB, and encountering a perplexing error that I couldn't find any specific information about on Node or JavaScript via Stack Overflow or Google. The troublesome section of my c ...

CSS responsive design: concealing elements does not prevent the page from being displayed

Imagine a scenario where I need to display a template in two different versions based on the user's device. For instance, I have utilized the following code: <div class="desktop"> <body> Hi Desktop user </body> </div> ...

Dealing with a large amount of HTML content following an Ajax request: best practices

I'm currently using a method that works fine, but I can't stop thinking about whether there might be a better way to achieve the same result. The task at hand is to display a user profile in a modal box. When a user clicks on a button or link, a ...

Updating the Backbone.js model within a MySQL database

I am facing an issue with my model setup: var Car = Backbone.Model.extend({ url: "/save.php", defaults: { color: "red" } }); Upon document ready, I initialize a new instance of the model and save it: new volvo = new Car({color:"gree ...

Exploring the concepts of recursion and return statements in JavaScript

Currently, I am immersing myself in the world of JavaScript by taking courses on CodeAcademy.com. However, there is one exercise question that is giving me some trouble, even though I believe I have come up with the correct answer. This particular code is ...

Analyzing arrays and object key/value pairs based on a specific value in javascript

I want to create a new object with key/value pairs. The new object should include values from an existing key/value object as well as unique values from an array. Here is the array: [{ name: "Computer", name: "Car", name: "House&q ...

Best practices for managing backend errors with Next.js 14

Currently, I am developing a project in Next.js 14 and I have set up my API requests using fetch within a handler.tsx file as shown below: async function getPositions() { const response = await fetch( process.env.BASE_API_URL + "/positions?enabl ...

Is it possible to pass a component into a dialogue box in material-ui using React?

Hello, I am currently facing an issue with displaying a chart component within a dialogue box. Despite having the code in place, the chart is not rendering inside the dialogue box as expected. Unfortunately, due to the complexity of the code, I am unable t ...

Exploring the world of Django context processors and middleware

I'm facing an issue while attempting to establish a context variable within my custom context processor utilizing a request variable. The request variable I am attempting to utilize is defined in my personalized middleware. However, the error message ...

Achieving a Transparent Flash overlay on a website without hindering its usability (attention, interaction, form submissions, etc.)

Currently, we are attempting to overlay a transparent flash on top of an iframe which loads external websites. Is there a method to configure the page in a way that allows the transparent flash to be displayed while still allowing interaction with the und ...

What are the best practices for managing live notifications with WebSocket technology?

I have developed a real-time chat application in React.js with Socket.io, but I want to implement a new feature. Currently, User A and User B can only communicate if they both have the chat open. I would like to notify User B with a popup/notification wh ...

Struggling to modify a document in a MongoDB collection with an HTTP Put request?

I've recently started working with AngularJS and I encountered an issue while trying to update my MongoDB Database. I'm facing a problem when attempting to update an object within my collection. The code snippet below showcases my approach: //li ...

I'm having trouble navigating in react-router 4, the route keeps redirect

Can someone help me figure out why all the links are redirecting to a blank page? The dependencies I'm using are: "react-router": "^4.2.0", "react-router-dom": "^4.1.1", App.js import { BrowserRouter, Route, Switch } from 'react-router-dom&ap ...

When the browser window is resized to mobile view, a div is overlapped by an image

I've encountered an issue with the image size and position when resizing to mobile view in the browser. .extension { display: table; padding: 50px 0px 50px; width: 100%; height: auto; color: #fff; background-color: #558C89; ...

Understanding the use of "el" in a function parameter in Vue Js

I am new to VueJS, so please be patient with me. I am trying to code a function that will scroll to an element with a specific ID when a "?" is used in the URL. I want it to have the same effect as demonstrated here. My assignment requires me to follow a ...

jQuery parallax effect enhances scrolling experience with background images

My website features a parallax design, with beautiful high-resolution images in the background that dominate the page. Upon loading the site, the landing page showcases a striking, large background image alongside a small navigation table ('about&apos ...

Refresh a selection menu using a checkmark

Can you help me with a script to enable/disable a dropdown based on the checkbox status? <body onload="enableDropdown(false);"> <form name="form1" method="post" onload="enableDropdown(false);"> <input type="checkbox" name="others" oncl ...

Avoiding cheating in a JavaScript game

I am in the process of creating a JavaScript/JQuery game that resembles a classic brick breaker. The game includes features such as scoring, levels, and more. I have plans to add a leaderboard where users can submit their final scores. However, my concer ...