The Easy React-Supabase Authentication And Session Storage
Learn about storing user sessions and private routes with Supabase and React router v6!
One of the most best inventions in the world of web development in my opinion has been the Backend-as-a-Service model. As fantastical it sounds to not have to write it yourself, there are services like Firebase and Supabase out there which really do provide Authentication, Cloud storage and all the good stuff right out of the box.
I have recently been playing around with Supabase since it offers exactly the same functionalities as Firebase but with a PostgreSQL based environment. Insofar, I feel good about it.
In this article series, I want to present to you a way to handle User authentication and session storage with Supabase in React applications.
This may sound trivial at a first glance, but there are a lot of moving parts involved and I had to do a lot of research to find something that works just right for me. I hope it does for you as well.
Let’s dive in! 👇
The End Goal
Our end result web app should have the following basic characteristics:
It should have a landing page
It should allow for login and signup separately (meaning, in different routes)
It should have a private dashboard, accessible only to logged-in users
Then, our app should also have the following intermediate feature:
It should be able to keep users logged-in even after reloading the web page, and closing the tab
The stack we’ll be using will be composed of React with Tailwind CSS because that’s very much the default for me due to sheer quality and usability.
I’ll also be using react-router-dom version 6. So, if you want to follow along, my package.json
looks like this:
{
"name": "basics_advanced_sup",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@heroicons/react": "^2.0.16",
"@supabase/supabase-js": "^2.10.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.9.0"
},
"devDependencies": {
"@types/react": "^18.0.27",
"@types/react-dom": "^18.0.10",
"@vitejs/plugin-react": "^3.1.0",
"autoprefixer": "^10.4.14",
"postcss": "^8.4.21",
"tailwindcss": "^3.2.7",
"vite": "^4.1.0"
}
}
Project Setup
Let’s create a new React project with Vite and install our dependencies:
$ yarn create vite
# or
$ npm create vite@latest
Follow the instructions and get the project up and running. Now, follow the Tailwind manual from here to have it working as well.
Now, as far as CSS classes go, I’m not focusing on them because this tutorial is about learning Supabase authentication, so I’ll simply redirect you to my GitHub repo to pick them up from.
Now, let’s get to the good stuff.
The Project Structure
The final project structure we’ll be going with is this, and it’ll be immensely helpful to follow along if you made the same one in your own project: