Q:

Getting req.headers is undefined when trying to read from req object in NextJS

On page load, I try to fire off an authentication request if a token exists in local storage.
// utils.ts
const init = async () => {
    try {
        const token = window.localStorage.getItem('token');

        if (token) {
            axios.defaults.headers.common['x-auth-token'] = token;
            const { user } = await axios.get('/api/auth/load')

            console.log('user!', user);
        } else {
            delete axios.defaults.headers.common['x-auth-token'];
        }
    } catch (err) {
        console.log('There was an error with init: ', err);
    }
}

And my pages/api/auth/load.ts file:
export default async function load(req: TLoadUserRequest, res) {
    auth(req, res);
    const { id } = req.user;

    await connectDb();

    const user = await User.findById(id);

    return res.json(user);
}

The problem lies within my auth.ts, which throws an error,
TypeError: req.headers is not a function

Here it is:
// middleware/auth.ts
import jwt from 'jsonwebtoken';
import config from 'config';

export default (req, res) => {
    const token = req.headers('x-auth-token');
    if (!token) return res.status(401).json({ msg: 'No token. Authorization denied.' });

    try {
        const decoded = jwt.verify(token, config.get('jwtSecret'));
        req.user = decoded.user;
    } catch (err) {
        return res.status(401).json({ msg: 'Token is invalid' });
    }
};

When I use Node/Express, I don't get this error -- does NextJS' req object not have a headers property? How can I add it, so I can use it with axios like this?

A:

Your syntax is a bit wrong for getting a header value.
req.headers('x-auth-token')

Should be
req.headers['x-auth-token']

