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

204
Visualizações
Trying to display different nav items based on if a user is logged in

I am trying to set up an site so that when a user is logged in, the nav bar will display "logout", and if the user isn't logged in, then it will display "signup" and "login". Right now through insomnia I have tested that the login works properly and hits the route. The handlebars just doesn't seem to update based on whether session is loggedIn or not. Any help is much appreciated, and please let me know if you need anymore info on anything.

 {{#if loggedIn}}
            <button class="button is-light" id="logout">logout</button>
 {{else}}
            <a href="http://localhost:3001/signup" class="button is-primary"> <strong>Sign up</strong> </a>
            <a href="http://localhost:3001/login"class="button is-light"> <strong>Log in</strong> </a>
 {{/if}}

This is the route set up for user login

```router.post('/login', async (req, res) => {
`try {
const userData = await User.findOne({
  where: {
    email: req.body.email
  }
})`

if (!userData) {
  res.status(400).json({ message: "Incorrect email or password."});
  return;
}

const validPassword = await userData.checkPassword(req.body.password)

if (!validPassword) {
  console.log("YO")
  res.status(400).json({ message: "Incorrect email or password."})
  return;
}

req.session.save(() => {
  req.session.user_id = userData.id;
  req.session.loggedIn = true;

  res.json({ user: userData, message: 'You are now logged in!' });
});

} catch (err) { res.status(400).json(err)} })

And lastly this is the code server.js code showing using the session data

    const sess = {
    secret: 'Super secret secret',
    cookie: {},
    resave: false,
    saveUninitialized: true,
    store: new SequelizeStore({
    db: sequelize
    })
    };

    app.use(session(sess)); ```

SCRIPT FOR LOGIN PAGE
    const loginFormHandler = async (event) => {
    event.preventDefault();
  
    console.log("YO!!!!")

    const email = document.querySelector('#email-login').value.trim();
    const password = document.querySelector('#password-login').value.trim();
  
    if (email && password) {
      const response = await fetch('/api/users/login', {
        method: 'POST',
        body: JSON.stringify({email, password }),
        headers: { 'Content-Type': 'application/json' },
      });
  
      if (response.ok) {
        // If successful, redirect the browser to the profile page
        document.location.replace('/');
      } else {
        alert(response.statusText);
      }
    }
  };

about 4 years ago · Juan Pablo Isaza
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