Mike K
Mike K

Reputation: 6481

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?

Upvotes: 1

Views: 8753

Answers (4)

Rafiur Rahman Protik
Rafiur Rahman Protik

Reputation: 21

I don't know why I'd to use some changes but this is how my code works in these two platforms.

In Node.js it worked with: req.header('x-auth-token')

In Next.js it worked with req.headers['x-auth-token']

Upvotes: 0

sergiovalp
sergiovalp

Reputation: 1

I did it by the bad way, but, it works for me:

//Sending:
const config = {                
            headers: { Authorization: `Bearer ${ElToken}` }
        };

        const resp = await axios.post("/api/nd-data", consulta, config);


//API:
    if (req.method === "POST") {

       const i = req.rawHeaders.indexOf('Authorization');
       const token = req.rawHeaders[i+1];
       console.log("token api: ", token);

Upvotes: 0

k123
k123

Reputation: 428

Your syntax is a bit wrong for getting a header value.

req.headers('x-auth-token')

Should be

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

Upvotes: 6

Nazim
Nazim

Reputation: 367

According to the docs you should use req.getHeader(<headerName>) https://nodejs.org/api/http.html#http_request_getheader_name

Upvotes: -1

Related Questions