Learn to implement server-side authentication with Supabase using JWT validation and Express.js in this clear step-by-step guide.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Set Up Your Supabase Project
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
/protected
using a tool like Postman or cURL.Authorization
header: Bearer YOUR_ACCESS_TOKEN
.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.