Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

298
Views
How can I store my JWT Token in localstorage?

userAction.js -> Frontend, Action

export const login = (userID, password) => async (dispatch) => {
    try {
        dispatch({ type: USER_LOGIN_REQUEST });
       
        const url = "http://localhost:8080/authenticate/";
        const config = {
          auth: {
            username: userID,
            password,

          },
        };
    
        const data = {};
        const response = await axios.post(
            url, 
            data, 
            config,
            
        )

        dispatch({ type: USER_LOGIN_SUCCESS, payload: config});
        
 
        if (response.status === 200) {
          // Login succeeded
          const token = response.data.token;
          console.log("TOKEN\n" + token);
          config.token = response.data.token;
          console.log(response.data.token);
          
        }
        
        localStorage.setItem("userInfo", JSON.stringify(config) );
    }

My login function in REST Server :

exports.login = async (req,res) =>{

  const b64auth = (req.headers.authorization || '').split(' ')[1] || '';
  const [userID, password] = Buffer.from(b64auth, 'base64').toString().split(':');
  const user = await User.findOne({ userID: userID });
  if(!user) return res.status(400).send('User not found');
  const validPass = await bcrypt.compare(password, user.password);
  if(!validPass) return res.status(400).send('Incorrect Password');

  //const token = generateToken(user.userID);
  let payload = {
    userID: user.userID
  }
  const token = generateToken(userID);
  
  res.header('Authorization', 'Bearer ' + token).json(user);
  
  return token;
}

I generate my token this way :

const generateToken = (_id) => {
  console.log('Signing token for ID ', _id);
  console.log('Secret key is ', process.env.JWT_KEY);
  const token = jwt.sign({ _id}, process.env.JWT_KEY, {
    expiresIn: "30d",
  });
  console.log('Signed token: ', token);
  return token;
};

I try to store my token in my "userInfo" State .. but only username and password is displayed not token ..It works before .. but I don´t know why it´s not working anymore ^^ I´m completely at a loss

I hope someone sees the error

my Console gives me the detail:

TOKEN 
undefined
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

You are expecting response.data to be an object. In that case update your API handler to return property token in an object:

exports.login = async (req,res) =>{

  const b64auth = (req.headers.authorization || '').split(' ')[1] || '';
  const [userID, password] = Buffer.from(b64auth, 'base64').toString().split(':');
  const user = await User.findOne({ userID: userID });
  if(!user) return res.status(400).send('User not found');
  const validPass = await bcrypt.compare(password, user.password);
  if(!validPass) return res.status(400).send('Incorrect Password');

  //const token = generateToken(user.userID);
  let payload = {
    userID: user.userID
  }
  const token = generateToken(userID);
  
  return res.header('Authorization', 'Bearer ' + token).json({ user, token });
}

Hopefully that helps!

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!