reactjs - how to fetch headers in middleware in Next js - Stack Overflow

时间: 2025-01-06 admin 业界

In below NextJS code how can i access Authorization in middleware when client component call API every time api is call it show empty headers in middleware can some on explain it

Client Component:-

'use client'

import { useEffect } from "react";

export default function Page(){
    useEffect(()=>{
        const data = async () => {
            const log  = localStorage.getItem("login");
            let usr = await fetch("http://localhost:3000/api/route",{
                method: "GET",
                headers:{
                    "Content-Type": "application/json",
                    "Authorization": log
                } 
            });
            usr = await usr.json();
            console.log(usr);
        }
        data();
    },[]);
    return(
        <div>
            <h1>Login Middleware</h1>
        </div>
    );
}

API Route:-

import { NextResponse } from "next/server";

export function GET(request){
    return NextResponse.json({msg: "Api Call"});

}

Middleware :-

const { NextResponse } = require("next/server");

export function middleware(request){
    const head = request.headers;
    console.log(head);
    
}

export const config = {
    matcher: ["/login"],
}

In below NextJS code how can i access Authorization in middleware when client component call API every time api is call it show empty headers in middleware can some on explain it

Client Component:-

'use client'

import { useEffect } from "react";

export default function Page(){
    useEffect(()=>{
        const data = async () => {
            const log  = localStorage.getItem("login");
            let usr = await fetch("http://localhost:3000/api/route",{
                method: "GET",
                headers:{
                    "Content-Type": "application/json",
                    "Authorization": log
                } 
            });
            usr = await usr.json();
            console.log(usr);
        }
        data();
    },[]);
    return(
        <div>
            <h1>Login Middleware</h1>
        </div>
    );
}

API Route:-

import { NextResponse } from "next/server";

export function GET(request){
    return NextResponse.json({msg: "Api Call"});

}

Middleware :-

const { NextResponse } = require("next/server");

export function middleware(request){
    const head = request.headers;
    console.log(head);
    
}

export const config = {
    matcher: ["/login"],
}
Share Improve this question asked 23 hours ago GAMING WARRIORGAMING WARRIOR 91 silver badge1 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

You can access the authorization at your middleware like this :

const authHeader = request.headers.get("authorization");
console.log("Authorization Header:", authHeader);