Apoorv singh yadav
Apoorv singh yadav

Reputation: 41

Clerk Authentication - 401 Unauthorized despite valid session token in React app

Problem: I’m using Clerk authentication in my React app to manage user authentication. I’m trying to make an API request to my backend (Express.js) after the user has logged in successfully, but I keep receiving a 401 Unauthorized response. I’ve verified that the Clerk session is active, and the Authorization token seems to be passed correctly in the request headers.

Details:

Here is My frontend from where I'm sending req :


const Homepage = () => {

  const test = async () => {
   await fetch("http://localhost:3000/api/test", {
        credentials: "include",
      });
  };

return (
    <div className='homepage'>
        <Link to="/dashboard">Get Started</Link>
        <button onClick={test} >TEST BACKEND</button>
    </div>
  )
}

export default Homepage

Here is My Express Backend :

import express from "express";
import dotenv from 'dotenv';
import cors from "cors";
import {ClerkExpressRequireAuth} from "@clerk/clerk-sdk-node";

dotenv.config();

const port = process.env.PORT || 3000;

const app = express();

app.use(cors({
    origin: process.env.CLIENT_URL,
    credentials:true,
}))

app.use(express.json())

app.get("/api/test", ClerkExpressRequireAuth(), (req,res)=>{
    const userId = req.auth.userId;
    console.log(userId);
    res.send("Success!")
})

app.use((err, req, res, next) => {
    console.error(err.stack)
    res.status(401).send('Unauthenticated!')
})

app.listen(port, ()=>{
    connect()
    console.log("Server running on 3000")
})

Here is the Screenshot of my Network console of browser

Upvotes: 0

Views: 114

Answers (1)

Apoorv singh yadav
Apoorv singh yadav

Reputation: 41

The problem is coming because of the expired jwt token, which happened because of wrong system timings. once it was fixed the token is not expiring, and the problem was solved

Upvotes: 1

Related Questions