在哪里可以在Next.js应用中设置Sentry的设置?

发布于 2025-01-18 03:19:21 字数 1804 浏览 1 评论 0原文

我一直在尝试将用户数据设置到 Sentry 的全局范围内,因此每次出现错误或事件时,用户信息都会传递给它。

我的应用程序是在 Next.js 中构建的,因此我很自然地添加了 Sentry 的 Next.js 文档中的配置。

我不知道在哪里添加 Sentry.setUser({id: user.Id}) 方法以使其全局设置用户。

到目前为止,我已将其添加到 Sentry 的 _error.js 文件中的 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;

但是当尝试记录错误时,用户信息不会显示在 Sentry 中,仅显示默认用户 ip:

在此处输入图像描述

我也尝试在成功登录后设置用户,但仍然没有任何结果..

感谢帮助!

I have been trying to set user data into Sentry's scope globally, so every time there's an error or event, user info is passed to it.

My app is built in Next.js, so naturally I added the config as it is in Sentry's documentation for Next.js.

I haven't got the idea on where to add the Sentry.setUser({id: user.Id}) method in order for it to set the user globally.

So far I have added it to the Sentry's _error.js file, inside the getInitialProps method:

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;

But when trying to log errors, the user info doesn't show in Sentry, only the default user ip:

enter image description here

I have also tried setting the user after successful login, and still nothing..

Help is appreciated!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

赤濁 2025-01-25 03:19:22

不确定这是否是正确的方法,但上述解决方案对我不起作用。所以我尝试在 _app.tsx 中调用 setUser 。

import { useEffect } from "react";
import { setUser } from "@sentry/nextjs";
import { UserProvider, useUser } from "@auth0/nextjs-auth0";
import type { AppProps } from "next/app";

function SentryUserManager() {
  const { user } = useUser();

  useEffect(() => {
    if (user) {
      setUser({
        email: user.email ?? undefined,
        username: user.name ?? undefined,
      });
    } else {
      setUser(null);
    }
  }, [user]);
  return null;
}

export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <UserProvider>
      <Component {...pageProps} />
      <SentryUserManager />
    </UserProvider>
  );
}

仍然不确定为什么这对我有用而其他解决方案却不起作用,但认为值得分享。

Not sure if this is the right way, but the above solutions didn't work for me. So I tried calling setUser inside _app.tsx.

import { useEffect } from "react";
import { setUser } from "@sentry/nextjs";
import { UserProvider, useUser } from "@auth0/nextjs-auth0";
import type { AppProps } from "next/app";

function SentryUserManager() {
  const { user } = useUser();

  useEffect(() => {
    if (user) {
      setUser({
        email: user.email ?? undefined,
        username: user.name ?? undefined,
      });
    } else {
      setUser(null);
    }
  }, [user]);
  return null;
}

export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <UserProvider>
      <Component {...pageProps} />
      <SentryUserManager />
    </UserProvider>
  );
}

Still not sure why this worked for me and the other solutions didn't, but figured it was worth sharing.

落叶缤纷 2025-01-25 03:19:22

我建议使用设置哨兵用户上下文。

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);

I would suggest using the callback handler to set your Sentry user context.

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);

濫情▎り 2025-01-25 03:19:22

成功登录后,您可以立即将用户设置在哨兵中,

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

您可以在登录时清除用户

const handleLogout = {
  // Do othe stuff
  Sentry.configureScope(scope => scope.setUser(null));
}

You can set the user in Sentry right after successful login

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

Additionaly you can clear the user while logging out

const handleLogout = {
  // Do othe stuff
  Sentry.configureScope(scope => scope.setUser(null));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文