localStorage getItem works on a local .NET project, but returns NULL once deployed to a real environment

Viewed 40

I have a project that combines a .NET backend with React/Typescript frontend.

At some point, the backend (C#) executes the following instructions:

var name = AwesomeClass.GetName();
var surname = AwesomeClass.GetSurname();

var StorageScript = $"localStorage.setItem('name_token', '{name}'); localStorage.setItem('surname_token', '{surname}');";

ScriptManager.RegisterStartupScript(this, this.GetType(), "TokenLocalStorage", StorageScript, true);

Unless I'm doing something wrong (which is a clear possibility), that call to RegisterStartupScript executes the provided Javascript script, which will store in localStorage those "tokens". The name and surname variables are NOT null (tested several times).

On the frontend, there are calls to localStorage.getItem as follows:

const nameToken = localStorage.getItem('name_token');

The thing is that, if I run the project locally (through Visual Studio 2022, for example), everything works:

  • The call to localStorage.getItem works: the value generated in the backend is successfully retrieved from the frontend
  • Opening a Code Inspector (in Chrome, Firefox, Edge, etc) shows the entries in localStorage, as expected.

However, when the project is deployed on an AWS instance (so it can be access through a "real" URL, with its login form and so), the calls to localStorage.getItem ALWAYS return null. No matter which value is stored. No matter where the backend performs that RegisterStartupScript call. No matter where the frontend tries to retrieve the values. Always NULL.

The thing is that, through the Code Inspector, the tokens are present on the localStorage. So the backend part is working (it still storing the values using the setItem thing). Even more: if the localStorage.getItem is executed in the "Console" tab, the value returned is correct.

It seems that only the React/Typescript code is unable to retrieve the value.

Any idea of what could be the root cause?

I understand that problem might be located in the "deployment" process (AWS configuration? Pipeline configuration?), but want to be sure that there is nothing (obvious) wrong with the code.

Also, if there is another easy way to send backend data to the frontend, I'm all ears.

PD: Fairly new to the web development world, so I might be ignoring critical things.

0 Answers
Related