How to Set a Session Variable in JavaScript

To set a browser-only session value in JavaScript, call sessionStorage.setItem(key, value); to set a server session, send a request to an endpoint that writes the value on the server. These are different systems: JavaScript running in the browser cannot directly assign a PHP, ASP.NET, Express, or other server-side session variable. This guide shows how to choose the right approach, set the value, retrieve it, and verify that it works.

What a Session Variable Means in JavaScript

“Session variable” can mean several things, and choosing the wrong one causes most confusion.

  • A regular JavaScript variable exists only while the current page is loaded. It disappears on refresh.
  • sessionStorage is browser storage intended for data that should survive reloads in one tab but not become permanent.
  • A server-side session is data held by your application server and associated with a visitor through a session cookie or another session identifier.
  • An authentication cookie may identify a session, but JavaScript should not normally read that cookie when it is marked HttpOnly.

For example, this is only a page variable:

let selectedPlan = "pro";

Refreshing the page resets selectedPlan. This stores the value for the current browser tab’s session instead:

sessionStorage.setItem("selectedPlan", "pro");

Browser storage is controlled by browser JavaScript; server sessions are controlled by server code.

How to Set a Session Variable in JavaScript

Choose the storage location based on who needs the data and how long it should remain available.

Need Use Who Can Read It
Keep a UI choice during reloads in one browser tab sessionStorage JavaScript running on the same origin
Keep a value after the browser is closed and reopened localStorage or a server database Browser JavaScript or your server, depending on the choice
Store temporary state your backend needs A server-side session endpoint Your server; the browser receives only allowed data
Keep login credentials or session IDs inaccessible to JavaScript An HttpOnly secure cookie Your server

Step 1: Use sessionStorage for Browser-Only State

Use sessionStorage for temporary interface state such as a multi-step form draft, a selected tab, a filter, or a checkout screen value that does not need to be trusted by the server.

All sessionStorage values are strings. Store a simple value like this:

const key = "myapp:checkout:draftId";
const draftId = "order-1842";
sessionStorage.setItem(key, draftId);

Read it later with getItem():

const draftId = sessionStorage.getItem("myapp:checkout:draftId");
if (draftId !== null) {
  console.log(`Restored draft: ${draftId}`);
}

getItem() returns null when the key does not exist. Test for null rather than assuming a missing value is an empty string.

Use a clear, app-specific prefix such as myapp:. The storage area is shared by same-origin pages in the same tab or browsing context, so specific keys reduce collisions with other parts of your application.

Some privacy settings or embedded-page contexts can block browser storage. Handle that failure if the feature is optional:

function saveDraftId(draftId) {
  try {
    sessionStorage.setItem("myapp:checkout:draftId", draftId);
    return true;
  } catch (error) {
    console.error("Could not save browser session data:", error);
    return false;
  }
}

Step 2: Store Objects With JSON

For an object, array, or form state, convert the data to JSON before saving it. Convert it back when reading it.

const preferences = {
  theme: "dark",
  compactMode: true,
  visibleColumns: ["name", "status", "updatedAt"]
};
sessionStorage.setItem(
  "myapp:preferences",
  JSON.stringify(preferences)
);

Read it safely:

function getSessionPreferences() {
  const rawValue = sessionStorage.getItem("myapp:preferences");
  if (rawValue === null) {
    return null;
  }
  try {
    return JSON.parse(rawValue);
  } catch {
    sessionStorage.removeItem("myapp:preferences");
    return null;
  }
}
const preferences = getSessionPreferences();
console.log(preferences?.theme);

Do not treat browser storage as trusted input. A user, browser extension, or malicious script running through an XSS vulnerability can change it. Validate any value again on the server before using it for prices, permissions, account identity, or other security-sensitive decisions.

Step 3: Remove the Value When the Task Is Finished

Remove one value when the user completes, cancels, or abandons the related task:

sessionStorage.removeItem("myapp:checkout:draftId");

Use sessionStorage.clear() only when your application owns every key in that storage area:

sessionStorage.clear();

Clearing all storage can accidentally erase unrelated state saved by other pages on the same origin. Removing one named key is usually the safer finishing step.

Set a Server Session From Browser JavaScript

A browser script cannot run code such as $_SESSION["theme"] = "dark" or req.session.theme = "dark" directly. It must make an HTTP request, and the server endpoint must validate and store the value.

A typical flow is:

  1. The browser sends a POST request with a permitted value.
  2. The server identifies the visitor through its session cookie.
  3. The server validates the input and writes to its session store.
  4. The browser receives a success response or an error.

Here is an Express example. This is a minimal application setup for local development using express-session.

import express from "express";
import session from "express-session";
if (!process.env.SESSION_SECRET) {
  throw new Error("SESSION_SECRET must be set");
}
const app = express();
app.use(express.json());
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      sameSite: "lax",
      secure: process.env.NODE_ENV === "production"
    }
  })
);
app.post("/api/session/theme", (req, res) => {
  const allowedThemes = new Set(["light", "dark"]);
  const { theme } = req.body;
  if (!allowedThemes.has(theme)) {
    return res.status(400).json({ error: "Invalid theme" });
  }
  req.session.theme = theme;
  req.session.save((error) => {
    if (error) {
      return res.status(500).json({ error: "Could not save session" });
    }
    return res.json({ theme: req.session.theme });
  });
});
app.get("/api/session/theme", (req, res) => {
  res.json({
    theme: req.session.theme ?? null
  });
});
app.listen(3000);

Your page can set that server session value with fetch():

async function setTheme(theme) {
  const response = await fetch("/api/session/theme", {
    method: "POST",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ theme })
  });
  if (!response.ok) {
    throw new Error("Could not save theme preference");
  }
  return response.json();
}
setTheme("dark")
  .then((data) => console.log("Saved theme:", data.theme))
  .catch((error) => console.error(error));

For an application served from the same origin, credentials: "same-origin" ensures the browser includes the session cookie for that request. Avoid allowing arbitrary cross-origin sites to send credentialed requests to session endpoints. If your frontend and API use different origins, configure CORS narrowly, validate request origins, and use your application’s CSRF protection.

The default in-memory session storage commonly used in local Express setups is not suitable for a deployed application. Use a durable session store appropriate for your infrastructure before relying on server sessions in production.

Set a PHP Session From JavaScript

JavaScript cannot directly read or write $_SESSION. PHP runs on the server before the browser executes the page’s JavaScript, so create a PHP endpoint that updates the session.

For example, a save-theme.php endpoint can validate a JSON request and save an allowed preference:

<?php
declare(strict_types=1);
session_start();
header("Content-Type: application/json");
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);
    echo json_encode(["error" => "Method not allowed"]);
    exit;
}
$input = json_decode(file_get_contents("php://input"), true);
if (!is_array($input)) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid JSON"]);
    exit;
}
$theme = $input["theme"] ?? null;
$allowedThemes = ["light", "dark"];
if (!in_array($theme, $allowedThemes, true)) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid theme"]);
    exit;
}
$_SESSION["theme"] = $theme;
echo json_encode([
    "theme" => $_SESSION["theme"]
]);

Call that endpoint from the browser:

async function setPhpTheme(theme) {
  const response = await fetch("/save-theme.php", {
    method: "POST",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ theme })
  });
  if (!response.ok) {
    throw new Error("PHP session update failed");
  }
  return response.json();
}

Do not accept a user ID, role, account balance, or permission level from this request and write it directly into the session. Derive identity from the authenticated session already associated with the request, and validate every client-provided value against rules your server controls.

Read Server Session Data in JavaScript Safely

A server session may contain private data that the browser should never receive. Return only the specific value the page needs.

For example, this API response is reasonable for a UI preference:

{
  "theme": "dark"
}

A response containing internal permissions, password-reset state, access tokens, or administrative flags is usually not appropriate simply because the browser asked for it.

An HttpOnly session cookie is intentionally unavailable through document.cookie and sessionStorage. That is a security feature: it makes it harder for injected JavaScript to steal the session identifier. Your JavaScript does not need to read the cookie to use a same-origin server session; the browser sends it with qualifying requests automatically.

If a page needs initial session-derived state, either:

  • request a JSON endpoint after the page loads, or
  • render a carefully encoded value into the page from the server.

Avoid building JavaScript source by concatenating raw session values into a <script> tag. Use your server framework’s JSON serializer or a JSON API response so quotes and special characters are encoded safely.

Verify and Troubleshoot Session Storage

Check browser-only session data by opening your browser developer tools and inspecting the site’s Storage or Application panel. You should see the key and its string value under session storage for the current origin.

Use this quick check in the Console:

sessionStorage.getItem("myapp:checkout:draftId");

For a server session, verify the full request cycle:

  • The browser’s Network panel should show the POST request succeeding.
  • The response should contain the value the endpoint saved.
  • A later GET request should return the expected session value.
  • The session cookie should be present for the correct site, although an HttpOnly cookie will not be readable by JavaScript.

Common problems include:

  • Using localStorage when you meant sessionStorage, or the reverse.
  • Calling JSON.parse() on a missing or malformed storage value.
  • Opening a second tab and expecting it to share sessionStorage.
  • Making an API request to a different origin without sending or accepting the session cookie correctly.
  • Restarting a development server that uses only in-memory session storage.
  • Attempting to access an HttpOnly cookie from JavaScript.

Session Limits and Persistence

sessionStorage is useful for convenience, not for permanent records. It is generally tied to the current tab or browsing context and is normally removed when that browser session ends. A server session is also temporary by design; its lifetime is controlled by your application and its session cookie or server-side session store.

Cookie-dependent server sessions can fail to start when a visitor refuses cookies (University of Rochester). Data that must survive a later visit, such as an order, saved cart, account setting, or user-created work, should be stored durably in your database or another persistent system, not only in a session.

Never store access tokens, passwords, payment information, or authorization decisions in sessionStorage. Any JavaScript that runs on your origin can read it, including injected code in the event of an XSS flaw. Keep sensitive session identifiers in secure, HttpOnly cookies and keep authorization decisions on the server.

Choose sessionStorage for temporary browser interface state, and use a validated API endpoint for data your backend must keep in a server session.

Frequently Asked Questions

What Is a Session Variable?

A session variable is temporary data associated with a browser session or a server-side user session. In browser JavaScript, it often means a value stored with sessionStorage; on a server, it usually means data associated with a session ID stored in a cookie. The two kinds of session data have different locations, lifetimes, and security properties.

Can JavaScript Get a PHP Session Variable?

JavaScript cannot directly read PHP’s $_SESSION array because that array exists on the server. Create a PHP endpoint that calls session_start() and returns only the permitted value as JSON. The browser can then retrieve that JSON with fetch().

How Do I Get a Session Value on the Client Side?

For browser session storage, use sessionStorage.getItem("your-key"). It returns a string when the key exists and null when it does not. For a server session value, request a server endpoint that returns a deliberately limited JSON response.

Where Are Session Variables Stored?

sessionStorage values are stored by the browser for the site’s origin and current browser session. Server session variables are stored in server memory, a database, Redis, or another configured session store, while the browser commonly keeps only a session-identifying cookie. The browser should not receive the whole server session by default.

How Do I View Session Variables in the Browser?

Open browser developer tools and look for the site’s Storage or Application panel to inspect sessionStorage and localStorage keys. You can also run sessionStorage.getItem("your-key") in the Console. Server-side session contents are not normally visible in browser tools because they remain on the server.