Recently I built a single page application using vanilla JavaScript on the frontend and Rails as an api for the backend. One of the first issues I came across when building out this application was the inability for the frontend to communicate with the backend without sending a fetch
to my SessionsController
every single time.
The process of sending a fetch
every time I needed to check who was logged in and then sending another fetch
from the response
of the first fetch
to actually do what I needed to do didn’t seem very effective to me. This isn’t a huge issue in the grand scheme of things, however it got to be a bit tedious. My brain went down the rabbit hole of trying to learn how to use session cookies that are stored in your browser.
Unfortunately all of the documentation I found involved installing some type of middleware into my application that, probably because of a user error on my end, never worked properly for me. After a few hours of trying to get this to work I felt that I was stuck in the same place for too long, I decided that there had to be an easier way for me to store my logged in users id
on the frontend and after some digging I discovered the javascript object sessionStorage
. According to W3, ‘The … sessionStorage properties allow [you] to save key/value pairs in a web browser.’ This was the golden ticket I needed, and I’m going to explain to you how I used sessionStorage
in my application.
Having had my user
model set up, and the form for user
login/signup built, my issue kept arising when I would reload the page to reset my DOM. Each time the DOM would load my application would have no knowledge of the user that I had signed in or created before the reload. As a regular user of any website, my vision was that unless a user logged out explicitly, the session should persist. This isn’t a universal rule, however most websites (Amazon, Twitter, GitHub) don’t log a user
out when the user
closes or reloads the webpage, and if they did it would be a little annoying. The problem as I saw it was that my frontend needed to recognize that there was a user
logged in. This is what sessionStorage
was built for. Implementing this was simple; when a user
successfully logged in, set the id
of the user
to the key :user-id
inside of the sessionStorage
object.
fetch sent when user
is signed in
This set a key/value pair to persist throughout my application as is unless explicitly set to something else or reset. Anywhere in my application at any point during my session, sessionStorage.user_id
will return my current :user_id
. This is useful for several reasons. For starters, now when I load my DOM, I can set a conditional to check the sessionStorage
object.
#javascript #web-development #programming #developer