/supabase-tutorials

How to do server-side auth check in Supabase?

Learn to implement server-side authentication with Supabase using JWT validation and Express.js in this clear step-by-step guide.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to do server-side auth check in Supabase?

 

Step 1: Set Up Your Supabase Project

 

  1. Initialize a new Supabase project by visiting the Supabase website and setting up an account if you haven’t already.
  2. Once logged in, create a new project and name it according to your preference.
  3. Note the API URL and the API key as these will be required to connect to your database.

 

Step 2: Install Supabase Client

 

To interact with your Supabase backend, you need to install the Supabase client library in your project. If you're using Node.js, you can install it using npm:

npm install @supabase/supabase-js

 

Step 3: Initialize Supabase in Your Project

 

After installation, you need to initialize Supabase in your server-side code. Create a new JavaScript file (e.g., server.js) and write the following code:


const { createClient } = require('@supabase/supabase-js');

const supabaseUrl = process.env.SUPABASE\_URL;
const supabaseKey = process.env.SUPABASE\_KEY;

const supabase = createClient(supabaseUrl, supabaseKey);

Ensure you have environment variables SUPABASE_URL and SUPABASE_KEY set with your project's URL and API key, respectively.

 

Step 4: Implement Authentication Check

 

To check if a user is authenticated on the server-side, you must validate the JWT (JSON Web Token) received from the client. Here's how you handle this:


async function checkAuth(req) {
  const token = req.headers.authorization.split(' ')[1];
  const { data, error } = await supabase.auth.api.getUser(token);

  if (error) {
    console.error('Error fetching user:', error);
    return null;
  }

  return data;
}

Call this function in your server logic where you want to perform an auth check.

 

Step 5: Use the Auth Check in a Route

 

Assuming you're using an Express.js server, you can protect routes as follows:


const express = require('express');
const app = express();

app.get('/protected', async (req, res) => {
  const user = await checkAuth(req);

  if (!user) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  res.json({ message: 'Successfully authenticated', user });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Make sure you've set up your Express.js server correctly with necessary middleware like body-parser if required.

 

Step 6: Test Your Implementation

 

  1. Start your server and access the protected route /protected using a tool like Postman or cURL.
  2. Include the Authorization header: Bearer YOUR_ACCESS_TOKEN.
  3. Verify that you receive either an authenticated response or an error message if the token is invalid or absent.

 

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022