Validate your Express API back end with Clerk

·

1 min read

After spending many days with clerk docs, this seems to be the way to check if the user has an account in our application. There may be other ways to do the validation but I have not been lucky enough to find any blog or article that can help. So here is the simple code snippet.

import dotenv from 'dotenv';
dotenv.config();
const port = 5000;
import express from 'express';
import { Router } from 'express';
import cors from 'cors';
import jwt from 'jsonwebtoken';
import { Clerk } from '@clerk/backend';
const clerk = Clerk({ apiKey: process.env.CLERK_API_KEY });

// clerkcusom middleware to check the user is valid 
// from express backend
const clerkAuthCheck = async (req, res, next) => {
    try {
        const sessionToken = req.headers.__session;
        const { sub, sid } = jwt.decode(sessionToken);
        if (!sub || !sid) {
            return next('Invalid token');
        }
        const user = await clerk.users.getUser(sub);
        if (!user) {
            return next('User not found');
        }
        req.userId = sub;
        next(null, user);
    } catch (error) {
        next(error);
    }
};

const app = express();
const router = Router();

router.use(cors());

router.use(express.json());


router.get('/', clerkAuthCheck, (req, res) => {
    try {
        res.send(req?.userId);
    } catch (error) {
        res.send('error: ' + error);
    }
});

app.use(router);
app.listen(port, () => {
    console.log(`app running on port ${port}`);
});

Please do let me know if you find any other way to do it.