JavaScript
Session Variables
Web Development
Client-Side Scripting
Programming Guide

How to access Session variables and set them in javascript?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

The first thing to clarify is that browser JavaScript cannot directly read or write server-side session variables. If the session lives on the server, JavaScript must talk to the server through an HTTP request. If you only need per-tab client-side storage, then sessionStorage is the browser feature you want instead.

Server session versus browser sessionStorage

These two concepts are often confused:

  1. Server session data lives on the server and is usually linked to a session cookie.
  2. sessionStorage lives in the browser and is scoped to one tab or window.

Client-side JavaScript can access sessionStorage directly:

javascript
sessionStorage.setItem("theme", "dark");
const theme = sessionStorage.getItem("theme");
console.log(theme);

That is useful for UI preferences or temporary non-sensitive state. It is not the same thing as reading a server framework's session object.

To access server session variables, call an API

If your server stores session data, expose it through an endpoint. Here is a simple Express example using express-session:

javascript
1import express from "express";
2import session from "express-session";
3
4const app = express();
5app.use(express.json());
6
7app.use(
8  session({
9    secret: "replace-this-secret",
10    resave: false,
11    saveUninitialized: false,
12  })
13);
14
15app.get("/api/session", (req, res) => {
16  res.json({
17    userId: req.session.userId ?? null,
18    theme: req.session.theme ?? "light",
19  });
20});
21
22app.post("/api/session/theme", (req, res) => {
23  req.session.theme = req.body.theme;
24  res.json({ ok: true });
25});
26
27app.listen(3000);

On the browser side, JavaScript reads and updates that server session through fetch:

javascript
1async function loadSession() {
2  const response = await fetch("/api/session", {
3    credentials: "same-origin",
4  });
5  return response.json();
6}
7
8async function saveTheme(theme) {
9  await fetch("/api/session/theme", {
10    method: "POST",
11    headers: { "Content-Type": "application/json" },
12    credentials: "same-origin",
13    body: JSON.stringify({ theme }),
14  });
15}

This is the normal web pattern. The browser never reaches into server memory directly; it asks the server for data and sends updates back.

Embedding session-derived data in the page

If you only need the session value during the initial page render, the server can inject it into the HTML:

html
1<script>
2  window.bootstrapData = {
3    userId: "12345",
4    theme: "dark"
5  };
6</script>

Then client-side JavaScript can read it:

javascript
console.log(window.bootstrapData.theme);

This works well for server-rendered apps, but it is still the server deciding what to expose. It is not direct access to the internal session store.

Security and practical boundaries

Because sessions often contain sensitive state, do not mirror the whole session into JavaScript just for convenience. Expose only the data the UI needs.

Also remember that JavaScript cannot mark a cookie as HttpOnly or read an HttpOnly cookie. That is by design. If your authentication session depends on an HttpOnly cookie, the browser will send it automatically with requests, but client-side code cannot inspect it directly.

That distinction is one reason secure session architectures use server-managed sessions plus HttpOnly cookies rather than storing everything in local browser storage.

Common Pitfalls

The biggest mistake is assuming sessionStorage is the same as server session state. It is not. One is client-side tab storage, and the other is server-side application state.

Another common problem is trying to read framework session variables directly from frontend JavaScript. That is impossible unless the server exposes them through HTML or an API response.

Developers also forget credentials when using fetch. If session cookies are required, configure the request so the browser sends them appropriately for your application setup.

Finally, do not expose sensitive session data to the frontend unless the UI truly needs it. Keeping session state server-side is often the whole point.

Summary

  • Browser JavaScript cannot directly access server-side session variables.
  • Use sessionStorage only for client-side per-tab state.
  • To read or update server session data, call an API endpoint and let the server modify the session.
  • Server-rendered pages can embed selected session-derived values into HTML for initial use.
  • Treat session data as sensitive and expose only what the frontend actually needs.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.