Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
How do I transfer a jwt token from local storage on the web browser to the server backend?

I am currently designing a simple website, where users can log in as a normal user or as an admin. Right now I am coding out the portion for when the user wants to go to an admin only web page, and the server will retrieve the jwt token stored in the local storage on the web browser to validate it.

Local storage of web browser

This is what the local storage looks like

Here is the code for retrieving the jwt token

var verifyFn = {
verifyToken: function (req, res, next) {
    const authHeader = localStorage.getItem("jwt_token");
    console.log("THIS IS THE HEADER")
    console.log(authHeader)
    
    if (authHeader === null || authHeader === undefined ){
    return res.status(401).send({ message: 'not authenticated BEARER TOKEN ISSUE' });
    }

    const token = authHeader
    console.log("NEW TOKEN")
    console.log(token)
    jwt.verify(token, config.jwt.secret, { algorithms: ['HS256'] }, (err, decoded) => {
        if (err) return res.status(401).send({ message: 'not authenticated' });
        req.decodedToken = decoded;
        console.log("DECODED TOKEN: " + req.decodedToken)
        next();
    });
}

However, whenever I try to run the server and browse to the admin page, there will be an error saying 'localstorage is not defined'. As such, I am not sure about how I can retrieve the jwt_token from the web browser to the server back end.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

A server has no access to the browser's localStorage object, as it is accessible from the client only, and does not exist in the server context.

What is usually done is sending the token in an Authorization header. It looks like you are using Node, so consider the following example request using the fetch API on the client:

const jwtToken = localStorage.getItem('jwt_token')

fetch('your-api-url', {
  method: 'request method here',
  headers: {
     Authorization: `Bearer ${jwtToken}`
  },
  body: JSON.stringify(your request body here)
}).then(response => ...)

In the server, you can then get the JWT token by looking at the request headers, something like this:

var verifyFn = {
verifyToken: function (req, res, next) {
    let authHeader = req.headers['Authorization']
    // the auth header will have Bearer prepended, so remove it
    authHeader = authHeader.replace('Bearer ', '')
    console.log("THIS IS THE HEADER")
    console.log(authHeader)
    
    if (authHeader === null || authHeader === undefined ){
       return res.status(401).send({ message: 'not authenticated BEARER TOKEN ISSUE' });
    }

    const token = authHeader
    console.log("NEW TOKEN")
    console.log(token)
    jwt.verify(token, config.jwt.secret, { algorithms: ['HS256'] }, (err, decoded) => {
        if (err) return res.status(401).send({ message: 'not authenticated' });
        req.decodedToken = decoded;
        console.log("DECODED TOKEN: " + req.decodedToken)
        next();
    });
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda