Home > Software design >  How to use localStorage on server side in node.js?
How to use localStorage on server side in node.js?

Time:05-10

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 :)

CodePudding user response:

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

CodePudding user response:

You can set localStorage items by evaluating this expresion:

await page.evaluate(
      `window.localStorage.setItem('X', 'Y')`
);
  • Related