elena
elena

Reputation: 4178

Access localStorage from ejs template

I am trying to save some data sent by the server to an EJS template in localStorage on the client side. However, when I try to access localStorage in the template, I get localStorage is undefined.

Here is a part of my page.ejs:

<% localStorage.setItem('info', JSON.stringify({'user': user})) %>

where user is a value received from the server.

Is this possible?

Upvotes: 4

Views: 7908

Answers (3)

Jonathan
Jonathan

Reputation: 59

At the time of writing, you could do this:

<script>
  localStorage.setItem('data', <%- JSON.stringify(data) %>)
</script>

if data is a property in your locals object for the view.

Upvotes: 2

Skkkhsn Jjjskshs
Skkkhsn Jjjskshs

Reputation: 19

check this once its worked for me,

<script>
  let data =JSON.parse('<%- JSON.stringify(data) %>')
  localStorage.setItem("data", JSON.stringify(data))
</script>

and for accessing,

<script>
  let data = JSON.parse(localStorage.getItem("data"))
</script>

Upvotes: 2

jtlindsey
jtlindsey

Reputation: 4863

There are a few options depending on what you want to do. I came across this post looking to do something a little different but here is one way:

After the template renders and passes the data user, add a script tag to modify localStorage.

<!-- example.ejs --> 

<!-- check for user on page load --> 
<% if (typeof user != "undefined") { %>
  <!-- make user available to script tag -->
  <% var user = user %>

  <!-- use script tag to access ejs data and local storage -->
  <script>
    let user = <%- JSON.stringify(user) %>;
    localStorage.setItem('info', JSON.stringify({'user': user}));
  </script>
<% } %>

Upvotes: 2

Related Questions