почему req.headers.authorization пустой?

Я только начал изучать nextjs. Хочу сделать авторизацию на сайте. Авторизацию делаю по видео ULBI TV (https://www.youtube.com/watch?v=6dJV7VQ_pr8&list=PL6DxKON1uLOGd4E6kG6d5K-tsTFj-Deln&ab_channel=UlbiTV) - первое видео из плейлиста, по которому делаю. Только он все делает на express.js. Я хочу сделать то же самое, только на nextjs. Дошел до 8 урока, но столкнулся с проблемой что у меня у файле middleware.js переменная req.headers.authorization = undefined. 3-ий день не могу разобраться почему так. Ссылка на проект на github: https://github.com/VanyaShumilo1/next-blog-app. Помогите, пожалуйста.

actions/registration.js

import axios from "axios";
import {setUser} from "../reducers/userReducer";


export const registration = async (name, username, email, password) => {
    try {
        const response = await axios.post('http://localhost:3000/api/auth/reg', {
            name,
            username,
            email,
            password,
        })

        alert(response.data.message + "Created")
    } catch (e) {
        alert(e);
    }
}


export const login = (email, password) => {
    return async dispatch => {
        try {
            const response = await axios.post('http://localhost:3000/api/auth/auth', {
                email,
                password,
            })
            dispatch(setUser(response.data.user))
            localStorage.setItem('token', response.data.token)
            console.log(response.data)
        } catch (e) {
            alert(e);
        }
    }
}

pages/api/auth/reg.js

import connectMongo from "../../../utils/connectMongo";
import User from "../../../models/User";
import bcrypt from "bcrypt";

export default async function reg(req, res) {

    try {
        console.log("Connecting to mongo")
        await connectMongo()
        console.log("Connected to mongo")

        const {name, username, email, password} = req.body
        const candidate = await User.findOne({email})

        if (candidate) {
            return res.status(400).json({message: `User with email ${email} already exist`})
        }

        const hashPassword = await bcrypt.hash(password, 10)
        const user = await User.create({name: name, username: username, email: email, password: hashPassword})


        res.status(200).json({user})
    } catch (e) {
        console.log(e)
        res.json(e)
    }
}

pages/api/auth/auth.js

import connectMongo from "../../../utils/connectMongo";
import User from "../../../models/User";
import bcrypt from "bcrypt";
const jwt = require("jsonwebtoken")
import {secretKey} from '../../../config/default.json'

export default async function auth(req, res) {

    try {
        console.log("Connecting to mongo")
        await connectMongo()
        console.log("Connected to mongo")

        const {email, password} = req.body

        const user = await User.findOne({email})

        if(!user) {
            return res.status(404).json({message: "User not found"})
        }

        const isPasswordValid = bcrypt.compareSync(password, user.password)

        if(!isPasswordValid) {
            return res.status(400).json({message: "Invalid password"})
        }

        const token = await jwt.sign({id: user._id}, secretKey, {expiresIn: "1h"})

        //res.status(200).json({token, user})

        return res.json({
            token,
            user: {
                id: user._id,
                username: user.username,
                email: user.email
            }
        })


    } catch (e) {
        console.log(e)
        res.json(e)
    }
}

reducers/index.js

import {applyMiddleware, combineReducers, legacy_createStore as createStore} from "redux";
import {composeWithDevTools} from "redux-devtools-extension";
import thunk from "redux-thunk";
import userReducer from "./userReducer";

const rootReducer = combineReducers( {
    user: userReducer
})

export const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)))

reducers/userReducer.js

const SET_USER = "SET_USER"
const LOGOUT = "LOGOUT"

const defaultState = {
    currentUser: {},
    isAuth: false
}

export default function userReducer(state = defaultState, action) {
    switch (action.type) {
        case SET_USER:
            return {
                ...state,
                currentUser: action.payload.user,
                isAuth: true
            }
        case LOGOUT:
            localStorage.removeItem('token')
            return {
                ...state,
                currentUser: {},
                isAuth: false
            }

        default:
            return state
    }
}

export const setUser = user => ({type: SET_USER, payload: user})
export const logout = () => ({type: LOGOUT})

и сам middleware.js (в корне проекта (на одном уровне с папкой pages))

import {NextResponse} from "next/server";

export function middleware(req, res, next) {
    console.log("Middleware file")
    console.log(req.headers.authorization)
    NextResponse.next()
}

Ответы (0 шт):