0

I wonder what causes the problem.

I use Next.js with Next Auth to build my fullstack app and I am securing my API routes. In my API route, I am checking if user is authenticated - simply if there's token.

If there's no token, I want request to fail, send failed message and return immediately.

As this validation shows up in multiple API routes, I decided to outsource this as a seperate function.

checkIfAuthenticated.js

import { getToken } from 'next-auth/jwt';

const checkIfAuthenticated = async (req, res) => {
  const token = await getToken({ req });

  if (!token) {
    res.status(401).json({ message: 'Protected resource, no access granted.' });
    return;
  }
};

export default checkIfAuthenticated;

/api/articles/index.js

const handler = async (req, res) => {
  //If user is not authenticated, request will fail
  await checkIfAuthenticated(req, res);

  if (req.method === 'GET') {
    let client;
    try {
      client = await connectDb();
    } catch (error) {
      res.status(500).json({ message: 'Connecting to the database failed.' });
    }

    const database = client.db('mindescape');
    const collection = database.collection('articles');

    try {
      const articles = await collection.find({}).toArray();
      res.status(200).json({ articles: articles });
      client.close();
    } catch (error) {
      res.status(500).json({ message: 'Connecting to the database failed.' });
      client.close();
    }
  }
}

Why the execution isn't stopped and goes to another if block throwing that Cannot set headers after they are sent to the client error? I know what this error means that the API is sending multiple responses. However if I don't make checkIfAuthenticated as a seperate function and just paste it straight to the API route, it all works like a charm. So what the heck? :)

if (req.method === 'GET') {
//THIS CODE IS EXECUTED EVEN THO SHOULDNT
}

Thanks in advance :) Maciej

Maciej
  • 31
  • 4
  • It looks like you expect the return statement in checkIfAuthenticated to trigger a return from handler. Doesn't work like that, each function is independent. – James Apr 19 '23 at 17:42
  • Oh definitely youre right. I spent a long time working on this project. My mind isn't fresh now. Massive thanks for clearing it up. All the best mate :) – Maciej Apr 19 '23 at 17:57

0 Answers0