0

I'm using NodeJs + Ejs and sometimes I would like to do some stuff from JavaScript only if user session exists.

Here is my nodejs session part:

var express  = require('express');
var app      = express();
var session  = require('express-session');

app.use(session({
    secret: '*********',
    maxAge: 3600000 
}));
app.use(function(req, res, next){
    res.locals.session = req.session;
    next();
});

I can see session exists from ejs when, for example, Jack is logged in:

User: <%= session.user.name %>  --> User: Jack

But I don't know how to check if session.user exists from javascript. For example how to show alert if session.user exists ?

2
  • if (session.user)? But you don't show an alert from the server side, unless you just mean setting something for the client side. Commented Sep 9, 2017 at 15:56
  • @DaveNewton yes from client side Commented Sep 9, 2017 at 16:00

1 Answer 1

1

Simply tell it to the client side:

<script>
 const user = "<%= session.user.name %>";
 if(user) alert(user);
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

It seems the only solution. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.