Authenticate a User with a Cookie

August 10, 2022


Send Back a Cookie when a User logs in


Let's say we have a route called login. When the user submits a form it will take them to this route. The username & password will be checked to see if they're correct. If they are, will send them back a cookie & redirect them to the dashboard route. If they aren't, then we'll redirect them back to the index page.

Sending a cookie back with successful login


Authenticating Routes


We just got sent to the dashboard route. The cookie name & value will be checked, if they match the cookie we created then will display the dashboard page. This authentication will be repeated on an account page & any other page that the user can access when they're logged in.

Authenticating the cookie on any route


Deleting the Cookie when the User Logs Out


We're going to make a route called logout. There will be a link displayed on the dashboard & account pages. In the route we will clear the cookie & redirect the user back to index page.

Clear the cookie & redirect the user to index

Authenticating with just a cookie only isn't a good idea. You should be using session storage or passport to authenticate the user, but it's still a cool thing to learn.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.