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

Learn how to dynamically chain where conditions in Firebase without prior knowledge of how many conditions will be added

Currently, I am working on a project using Angular and firebase. My goal is to develop a function that can take two arguments - a string and an object, then return an Observable containing filtered data based on the key-value pairs in the object for a spe ...

Locate the closing anchor tag following the image

I need to locate the closing anchor tag that wraps an image with the class name "cat-image" in order to move a div right after it. However, I am unable to modify the HTML by adding IDs or classes to the anchor or image tags. Below is an example of the HTM ...

The appearance of my sidebar items' right border varies depending on the web browser being used

My sidebar item's right border appears differently in Mozilla and Chrome. How can I resolve this issue? Here are the images from both browsers: https://i.stack.imgur.com/YGkkz.png https://i.stack.imgur.com/JxNs3.png "use client"; import { ...

Utilizing Loops to Generate Unique CSS Designs on an HTML Page

View reference image ->Take a look at the reference image provided. ->In the image, a for loop is used to create box designs and displayed above. ->The goal is to change the background color and border color of all boxes using a single HTML cla ...

Guide to ensuring modal box only appears once all criteria are satisfied

On my website, I have a form that requests the user's personal information. After filling out the form, a modal pops up with a "Thank you for signing up" message. The issue is that even if all fields are left blank and the button is clicked, the modal ...

The personalized directive does not respond to modifications in attributes

I am in the process of creating a modal directive that will be used to display data tables. The directive has an attribute called modal-visible, which is initially set to false by default. If this value is true, the modal will be visible when loaded. Howev ...

Is it true that event.stopPropagation does not function for pseudoelements?

I am facing an issue with event handling in my ul element. The ul has three li children elements, and the ul itself has a useCapture event handler for click. In the click event handler, I successfully stop the event using event.stopPropagation(), and every ...

Show the text from the chosen option using jQuery with a button

Hey everyone, I have a question regarding a coding issue I'm facing. In this problem, I am unable to display the text from the selected option when I click the order button. The desired result is to show the selected option that I choose and display i ...

All you need to know about AngularJS and its $routeParams

Recently, I've been diving into AngularJS and came across an interesting issue. It seems that when I include $RouteParams in the injection of my AngularJS service using .service, but don't actually utilize $RouteParams, the service ceases to work ...

Increase the size of the embedded iframe in your Cordova application by using the pinch-to-zoom

I have been struggling with this issue for the past few days and am having trouble finding a solution.. I am trying to figure out how to embed an iframe in a cordova app (running on an iOS device) to display an external webpage while allowing users to pin ...

Issue with Nextjs 13: Unable to locate 'src/app/dashboard/layout.tsx' (deleted optional layout)

Deciding to start a fresh Nextjs 13.4.5 project, I set up an app directory. Within the app directory, I created a new dashboard directory and added page and layout components. Everything seemed to be functioning smoothly with two layout components - one i ...

In what way is the JavaScript file able to locate the dependencies following the execution of npm install?

Upon receiving a javascript file named "neededjavascriptfile.js" along with a package.json file, I am faced with the task of running it in an html index file while utilizing certain functions from the javascript file. After executing "npm install --omit=d ...

Error encountered during Heroku deployment: "sh: 1: tailwind: not found"

package.json: "devDependencies": { "tailwindcss": "^0.7.4" }, "scripts": { "tailwind:css": "tailwind build src/css/tailwind.src.css -c tailwind.js -o src/css/tailwind.css", "start": "npm run tailwind:css && react-scripts start", ...

Create your own unique Semantic UI themes using the Semantic UI theme builder, complete with support for Font Awesome classnames and the ability to preview them with the

My admiration for Semantic UI and Semantic UI React knows no bounds. Not only are they phenomenal libraries, but their documentation is truly a work of art. Yet, crafting and keeping up with themes for these components can be quite the challenge. The task ...

Running Windows commands from Node.js on WSL2 Ubuntu and handling escape sequences

When running the following command in the CMD shell on Windows, it executes successfully: CMD /S /C " "..\..\Program Files\Google\Chrome\Application\chrome.exe" " However, attempting to run the same comman ...

Error encountered: API key is required - Issue found in: /node_modules/cloudinary/lib/utils.js at line 982

I encountered an issue with cloudinary while trying to upload photos on my website after adding a new function for Facebook login. "/home/ubuntu/workspace/YelpCamp/node_modules/cloudinary/lib/utils.js:982 throw "Must supply api_key"; ^ Mus ...

What is the method for sending raw put data using the request npm package in a Node.js environment

How can I hit an API using the "require" npm package in Node? The API requires raw PUT data instead of PUT fields. Can anyone please guide me on how to achieve this using the request npm package? For example, here is the raw PUT data that needs to be sent ...

Unlock the power of AJAX in your WordPress site

I've been exploring the realm of Javascript and AJAX lately. I feel like I'm so close to getting it right, but there's something off with how I'm integrating WordPress ajax functions. I've spent a lot of time going through the docu ...

I'm having difficulty mocking a function within the Jest NodeJS module

I have a module in NodeJS where I utilize a function called existsObject to validate the existence of a file in Google Storage. While testing my application with Jest 29.1.2, I am attempting to create a Mock to prevent the actual execution of this functio ...

HTML / CSS / JavaScript Integrated Development Environment with Real-time Preview Window

As I've been exploring different options, I've noticed a small but impactful nuance. When working with jQuery or other UI tools, I really enjoy being able to see my changes instantly. While Adobe Dreamweaver's live view port offers this func ...