Accessing local storage from ejs template
I am trying to store some data sent by the server into an EJS template in localStorage on the client side. However, when I try to access localStorage in the template, I get localStorage undefined.
Here is a portion of my page.ejs:
<% localStorage.setItem('info', JSON.stringify({'user': user})) %>
where user is the value retrieved from the server.
Is it possible?
+3
source to share
1 answer
There are several options depending on what you want to do. I came across this post to do something a little different, but here's one way:
After the template renders and passes the data user
, add a script tag to change 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>
<% } %>
+1
source to share