Clerk Middleware Issue: Getting 401

30 views Asked by At

I am new to Nextjs. I have some datastored in my database and when I am trying to fetch that data I am getting 401.

Clerk: The request to /api/JobsDisplay/TestFolder/user_2eCdNXtuzbEvJFXhhQKddqf4f5T is being protected (401) because there is no signed-in user, and the path is included in apiRoutes. To prevent this behavior, choose one of:

  1. To prevent Clerk authentication from protecting (401) the api route, remove the rule matching "/api/JobsDisplay/TestFolder/user_2eCdNXtuzbEvJFXhhQKddqf4f5T" from the apiRoutes array passed to authMiddleware
  2. To make the route accessible to both signed in and signed out users, add "/api/JobsDisplay/TestFolder/user_2eCdNXtuzbEvJFXhhQKddqf4f5T" to the publicRoutes array passed to authMiddleware
  3. To prevent Clerk authentication from running at all, pass ignoredRoutes: ["/((?!api|trpc))(_next.*|.+\.[\w]+$)", "/api/JobsDisplay/TestFolder/user_2eCdNXtuzbEvJFXhhQKddqf4f5T"] to authMiddleware
  4. Pass a custom afterAuth to authMiddleware, and replace Clerk's default behavior of redirecting unless a route is included in publicRoutes

Middleware.ts

import { authMiddleware } from "@clerk/nextjs";
 
export default authMiddleware({
  publicRoutes:["/", "/about", "/pricing", "/chatBox", "/api/webhooks/users", "/api/JobsDisplay/TestFolder"]
});
 
export const config = {
  matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};

userID.ts

// pages/api/applications/[userId].ts
import { MongoClient } from 'mongodb';
import type { NextApiRequest, NextApiResponse } from 'next';

const uri = 'mongodb://localhost:27017';
const dbName = 'test';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  console.log("Request received for userId:", req.query.userId);
  const client = new MongoClient(uri);
  try {
    console.log("Connecting to MongoDB...");
    await client.connect();
    console.log("Successfully connected to MongoDB.");

    const db = client.db(dbName);
    const { userId } = req.query;

    console.log(`Fetching data for userId: ${userId}`);
    const applications = await db.collection('applications').find({ userId: userId }).toArray();
    console.log("Applications found:", applications);

    if (applications.length === 0) {
      return res.status(404).json({ message: 'No applications found for the provided userId.' });
    }

    res.status(200).json(applications);
  } catch (error) {
    console.error('Error while fetching data:', error);
    res.status(500).json({ message: 'Failed to connect to MongoDB.' });
  } finally {
    await client.close();
  }
}

enter image description here

0

There are 0 answers