Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
Javascript annotations / decorators on normal functions

I am developing a Next.js application, and I have an API defined in the following way:

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'GET') {
    fn1Get(req, res);
  } else if (req.method === 'POST') {
    fn1Post(req, res);
  } else {
    res.status(501).json({ operation: `${req.method}: not implemented` });
  }
}
async function fn1Get(
  req: NextApiRequest,
  res: NextApiResponse
): Promise<void> {
  const authenticated = await checkAuth(req, res);
  if (authenticated) {
      // Get Stuff
      res.status(200).json({status: 'all right!'});
  }
}
async function fn1Post(
  req: NextApiRequest,
  res: NextApiResponse
): Promise<void> {
  const authenticated = await checkAuth(req, res);
  if (authenticated) {
      // Post Stuff
      res.status(201).json({status: 'all right!'});
  }
}
const checkAuth = async (req: NextApiRequest, res: NextApiResponse) => {
  const tokenValid = await extnernalApiCall(getToken(req));
  if (!tokenValid) {
    res.status(403).json({ error: 'Authentication Failed' });
  }
  return tokenValid
};

I am trying to find an easier setup to define authenticated methods, instead of adding inside of them the line const authenticated = await checkAuth(req, res);

In other languages like Java or Python I could use decorators / annotations / AOP, something like:

@checkAuth
async function fn1Get(
  req: NextApiRequest,
  res: NextApiResponse
):

Can I do something close to it in javascript? Maybe via wrapping functions, and/or using bind/call/apply??

Pseudo-code example:

const checkAuth = async (fn) => {
  const req = arguments[1];
  const res = arguments[2];
  const tokenValid = await extnernalApiCall(getToken(req));
  if (!tokenValid) {
    res.status(403).json({ error: 'Authentication Failed' });
  }
  return fn(arguments);
}
async function fn1Get = checkAuth(_fn1Get(
  req: NextApiRequest,
  res: NextApiResponse
): Promise<void> {
  const authenticated = await checkAuth(req, res);
  if (authenticated) {
      // Get Stuff
      res.status(200).json({status: 'all right!'});
  }
})

As you can see, all the functions that I want to authenticate will receive the same two parameters req and res (request and response), and my authentication function also need both parameters to get the token to authenticate from the req and write a 403 in res if it is not authenticated

The technologies I'm using are Next.js with React 17, TypeScript, ECMA6

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Yes, you can achieve this with a wrapper function (that's basically what decorators are anyway). That wrapper function has to return a function. Something like the following (you'll have to adjust the types accordingly):

const checkAuth = (fn) => {
  return async (req: NextApiRequest,res: NextApiResponse): Promise<void> => {
    const tokenValid = await extnernalApiCall(getToken(req));
    if (!tokenValid) {
      res.status(403).json({ error: 'Authentication Failed' });
    } else {
      fn(req, res);
    }
  }
}

const fn1Get = checkAuth((
  req: NextApiRequest,
  res: NextApiResponse
): Promise<void> => {
  // Get Stuff
  res.status(200).json({status: 'all right!'});
})

Having said that, I'm not familiar with next.js. There might be a way to register middelware handlers that would fire on every request without you having to wrap every handler explicitly.

about 4 years ago · Juan Pablo Isaza Report

0

I use next js along with next-auth for authentication. I made a function that checks if the request has a session. If no session, the user gets redirected to the sign in page. If the user has a session, it passes the props to getServerSideProps function.

import { getSession } from "next-auth/react";

/* gssp =  */
export const requireAuth = (gssp) => {
  return async (ctx) => {
      const { req } = ctx;
      const session = await getSession({ req })
      if (!session) {
          return {
              redirect: { permanent: false, destination: '/api/auth/signin' }
          };
      };
      const ctxWithSession = { ...ctx, session };
      return await gssp(ctxWithSession);
  };
};

Then, i call this function in my next js page as a higher function of getServerSideProps :

export const getServerSideProps = requireAuth(async _ctx => {
    const { session } = _ctx;
    return {
        props: {
          session: session,  
        },
    };
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!