This is how user authentication typically works:
First, the user will fill out a form, providing the necessary credentials. The credentials will be transferred to a controller in the backend.
The controller will try to match the credentials to the ones stored in the database. If the match is successful, the user is successfully authenticated. In this case, the controller will send a piece of user information back to the frontend, which will be stored inside the browser.
As long as this information exists, the user is considered authenticated and will not be required to provide credentials again.
So, before we can talk about how to create a user authentication system, you must first understand how to store a piece of data inside the user's browser, and that's what we are going to cover in this lesson.
Cookies
There are mainly four ways to store data in the browser: cookies, localStorage
, sessionStorage
, and IndexedDB.
A cookie is a small piece of string data stored in the user's browser. It is primarily used for user authentication and personalization. You can set a cookie using the document.cookie
setter like this:
1document.cookie = "<name>=<value>";
The cookie name is unique. If you set multiple cookies with the same name, only the latest one will be preserved.