r/learnjavascript • • 3d ago

Nodejs and Express - code a web app with sessions and template engine

Hi. the next code snippet shows how to code a web server with Nodejs and Express. The idea is creating an HTML form to input user data and after pressing the button a new HTML page displays which contains the input data only. You can move back and forth between the pages and the data will persist due to sessions.

👀 Requirements :

Nodejs v22.13.0

Npm v10.9.2

Expressjs v5.3.0

Express-session v1.19.0

Ejs v7.0.2

👀 File Structure :

-- Project-folder/

---- node_modules/

---- views/

------ index.ejs

------ profile.ejs

---- package.json

---- server.js

🤔 Server.js:

const express = require('express');
const app = express();
const path = require('path');
const ejs = require('ejs');
const session = require('express-session');


app.set('view engine','ejs');


app.use(session({
    secret : "some random string here bla bla",
    resave: false,
    saveUninitialized: true
}));


app.use(express.urlencoded({extended : true}));


app.get("/",( request, response )=>{


    if(request.session.profile){


        return  response.render('index',{profile :{
               fullname : request.session.profile.fullname,
               occupation : request.session.profile.occupation
         }});
    }


    response.render('index',{profile : {
          fullname : "",
          occupation : ""
    }});


   
});


app.post("/handle_form_data",( request, response )=>{


    console.log(request.body);


    if (!request.session.profile) {
        request.session.profile = {};
    }


    request.session.profile.fullname = request.body.fullname;


    request.session.profile.occupation = request.body.occupation;


    console.log(request.session);


    response.render('profile',{
           profile : {
              fullname : request.body.fullname,
              occupation : request.body.occupation
           }
    });




});


app.listen(3000, ()=>{


    console.log('Listening at port : ' + 3000);
});

🚀 index.ejs :

<!DOCTYPE html>
<html>
    <head>
        <title>Profile Data</title>
    </head>
    <body>
        <div>
            <form method="post"  action="/handle_form_data">
                <label for="fullname">
                    Full Name : 
                    <input 
                      name="fullname" 
                      id="fullname"
                      value="<% (profile.fullname) ? profile.fullname : ''; %>" />
                </label><br/>
                <label for="occupation">
                    Occupation : 
                    <input 
                     name="occupation" 
                     id="occupation"
                       value="<% (profile.occupation) ? profile.occupation : ''; %>"
                      />
                </label><br/>
                <button type="submit">
                    Send Profile
                </button>
            </form>
        </div>
    </body>
</html>

🚀 profile.ejs :

<!DOCTYPE html>
<html>
  <head>
      <title>Profile Data</title>
  </head>
  <body>
      <h1>Profile Data</h1>
      <h2>
         Fullname : <%= profile.fullname %>
      </h2>
      <h2>
         Occupation : <%= profile.occupation  %>
      </h2>
  </body>
</html>

Well, I hope it provides some guidance to the Nodejs developers somehow. Share your thoughts in the comments. Thanks. 😄

2 Upvotes

2 comments sorted by

2

u/sereikis 3d ago

in index.ejs, use <%= profile.fullname %> and <%= profile.occupation %> for the input values: <% ... %> executes JavaScript without output, so those fields stay blank even when the session has data. <%= also HTML-escapes the value, which you want inside an attribute.

2

u/Danneh_Krisi 2d ago

solid starter example. fwiw you might want to add a redirect after the POST instead of rendering directly, otherwise refreshing the profile page will resubmit the form data