Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

354
Visualizações
¿Dónde configurar el setUser de Sentry en la aplicación Next.js?

He estado tratando de configurar los datos del usuario en el alcance de Sentry a nivel mundial, por lo que cada vez que hay un error o evento, se le pasa la información del usuario.

Mi aplicación está integrada en Next.js, así que, naturalmente, agregué la configuración tal como está en la documentación de Sentry para Next.js.

No tengo la idea de dónde agregar el método Sentry.setUser({id: user.Id}) para que configure al usuario globalmente.

Hasta ahora lo he agregado al archivo _error.js de Sentry, dentro del método getInitialProps:

 import NextErrorComponent from 'next/error'; import * as Sentry from '@sentry/nextjs'; import { getUser } from '../lib/session'; const MyError = ({ statusCode, hasGetInitialPropsRun, err }) => { if (!hasGetInitialPropsRun && err) { Sentry.captureException(err); } return <NextErrorComponent statusCode={statusCode} />; }; MyError.getInitialProps = async (context) => { const errorInitialProps = await NextErrorComponent.getInitialProps(context); const { req, res, err, asPath } = context; errorInitialProps.hasGetInitialPropsRun = true; const user = await getUser(req, res); // Set user information if (user) { console.log('Setting user'); Sentry.setUser({ id: user.Id }); } else { console.log('Removing user'); Sentry.configureScope(scope => scope.setUser(null)); } if (res?.statusCode === 404) { return errorInitialProps; } if (err) { Sentry.captureException(err); await Sentry.flush(2000); return errorInitialProps; } Sentry.captureException( new Error(`_error.js getInitialProps missing data at path: ${asPath}`), ); await Sentry.flush(2000); return errorInitialProps; }; export default MyError;

Pero al intentar registrar errores, la información del usuario no se muestra en Sentry, solo la IP de usuario predeterminada:

ingrese la descripción de la imagen aquí

También intenté configurar el usuario después de un inicio de sesión exitoso, y todavía nada.

Se agradece la ayuda!!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Sugeriría usar el controlador de devolución de llamada para configurar el contexto de usuario de Sentry.

 import { handleAuth, handleLogin, handleCallback } from "@auth0/nextjs-auth0"; import * as Sentry from "@sentry/nextjs"; import { NextApiHandler } from "next"; const afterCallback = (_req, _res, session, _state) => { Sentry.setUser({ id: session.user.sub, email: session.user.email, username: session.user.nickname, name: session.user.name, avatar: session.user.picture, }); return session; }; const handler: NextApiHandler = handleAuth({ async login(req, res) { await handleLogin(req, res, { returnTo: "/dashboard", }); }, async callback(req, res) { try { await handleCallback(req, res, { afterCallback }); } catch (error) { res.status(error.status || 500).end(error.message); } }, }); export default Sentry.withSentry(handler);
about 4 years ago · Juan Pablo Isaza Relatório

0

Puede configurar el usuario en Sentry justo después de iniciar sesión correctamente

 const handleLogin = { try { const res = await axios.post("/login", {"john@example.com", "password"}) if (res && res?.data) { // Do other stuff Sentry.setUser({ email: "john@example.com" }); } } }

Además, puede borrar el usuario al cerrar la sesión

 const handleLogout = { // Do othe stuff Sentry.configureScope(scope => scope.setUser(null)); }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda