Send session data to static files in NodeJS

One of my NodeJS routes looks like this:

app.get('/test1/', function(req, res) {
    res.redirect("index.html");
});

And just underneath that I serve the static files:

app.use(express.static(__dirname, '/public'));
app.use(bodyParser.urlencoded({ extended: false }));

I understand what the first code block does, but not so much the second block. Although there is a HTML file in the /public directory, the index.html dependencies - JavaScript and CSS files - are in other folders at the same level of /public/.

Besides that, I set up a session variable which holds the username of the user. I would like to send this username to the JavaScript file which is called when index.html is redirected to in the route codeblock.

Is this possible with JavaScript & HTML?

A browser makes a request to your server, GET /, the routes are matched in that order, so it is matched with /test, and if it doesn't match it goes on to the second route, that is, express.static middleware.

The second route serves a static directory in the server. So express.static will match every file in the public directory. so GET /index.html will be served as well as GET /scripts/main.js.

If you want to send a session variable, you send the user cookies. To send a cookie set it on the response parameter within a middleware.

app.use('/test1/', function(req, res) {
  res.cookie('key', 'value');
  res.render('stuff');
});