Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda