Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

498
Vistas
How to use localStorage on server side in node.js?

I'm trying to access Browser localStorage from the server side. I have tried it using node-localStorage, store and store2 node libraries but nothing worked. When I checked the browser localStorage it was empty.

This my test.js

import playwright from 'playwright-core';
import response from '../token.json' assert {type: "json"};
import { LocalStorage } from "node-localstorage";
global.localStorage = new LocalStorage('./scratch');

(async () => {

    const browser = await playwright["chromium"].launch({
        headless: false,
        slowMo: 2000
    });

    const context = await browser.newContext();

    const page = await context.newPage();

    await page.goto("http://localhost:3000/trader-desktop/login");

    localStorage.setItem('token', response.token);
    localStorage.setItem('tokenType', response.tokenType);
    localStorage.setItem('tokenExpirationTime', response.tokenExpirationTime);
    localStorage.setItem('userId', response.userId);
    localStorage.setItem('realms', JSON.stringify(response.realms));
    localStorage.setItem('phone', response.phone);

    await page.goto("http://localhost:3000/trader-desktop/account-selection")

    await page.pause();
    
    await browser.close();

})();

This is my package.json file

{
    "type" : "module",
    
    "devDependencies": {
        "playwright": "1.21.1"
    },

    "dependencies": {
        "node-fetch": "^3.2.4",
        "node-localstorage": "^2.2.1",
        "store2": "^2.13.2",
        "type": "module"
    }
}

Is there a way I can work this thing out? I can't use window.localStorage because window is not defined in node.

Thanks in advance :)

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I used this and it worked like a charm. Thanks to all your contributions.

const fs = require('fs');

const localStorage = fs.readFileSync('../localStorage.json', 'utf8')

    const deserializedStorage = JSON.parse(localStorage)
    await page.evaluate(deserializedStorage => {
        for (const key in deserializedStorage) {
            if (key === "realms") {
                localStorage.setItem(key, JSON.stringify(deserializedStorage[key]));
            }
            else {
                localStorage.setItem(key, deserializedStorage[key]);
            }
        }
    }, deserializedStorage);

Source

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can set localStorage items by evaluating this expresion:

await page.evaluate(
      `window.localStorage.setItem('X', 'Y')`
);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda