Que fait sentry-nextjs-sdk ?
Configuration complète du SDK Sentry pour Next.js. À utiliser lorsqu'on demande « ajouter Sentry à Next.js », « installer @sentry/nextjs », ou configurer la surveillance des erreurs, le tracing, la relecture de session, la journalisation, le profilage, la surveillance IA ou les crons pour les applications Next.js. Prend en charge Next.js 13+ avec App Router et Pages Router.
Installation
npm install @sentry/nextjs
# ou
pnpm add @sentry/nextjs
# ou
yarn add @sentry/nextjs
Configuration
Créez les fichiers de configuration suivants à la racine de votre projet Next.js :
sentry.client.config.ts ou sentry.client.config.js
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: "VOTRE_DSN_SENTRY",
tracesSampleRate: 1.0,
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
integrations: [
new Sentry.Replay(),
],
});
sentry.server.config.ts ou sentry.server.config.js
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: "VOTRE_DSN_SENTRY",
tracesSampleRate: 1.0,
});
sentry.edge.config.ts ou sentry.edge.config.js
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: "VOTRE_DSN_SENTRY",
tracesSampleRate: 1.0,
});
Pour l'App Router
Ajoutez le fournisseur Sentry dans votre app/layout.tsx :
import { Sentry } from "@sentry/nextjs";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="fr">
<body>
<Sentry.ErrorBoundary fallback={<p>Une erreur est survenue</p>}>
{children}
</Sentry.ErrorBoundary>
</body>
</html>
);
}
Pour le Pages Router
// pages/_app.tsx
import { useEffect } from "react";
import type { AppProps } from "next/app";
function MyApp({ Component, pageProps }: AppProps) {
useEffect(() => {
// Initialisation côté client
import("@sentry/nextjs").then((Sentry) => {
Sentry.init({
dsn: "VOTRE_DSN_SENTRY",
tracesSampleRate: 1.0,
});
});
}, []);
return <Component {...pageProps} />;
}
export default MyApp;
next.config.js
const { withSentryConfig } = require("@sentry/nextjs");
const nextConfig = {
// Votre configuration Next.js existante
};
module.exports = withSentryConfig(nextConfig, {
silent: false,
hideSourceMaps: true,
widenClientFileUpload: true,
transpileClientSDK: true,
tunnelRoute: "/monitoring",
});
Variables d'environnement
Assurez-vous de définir les variables d'environnement suivantes :
SENTRY_DSN=votre_dsn
SENTRY_AUTH_TOKEN=votre_token_auth
SENTRY_ORG=votre_organisation
SENTRY_PROJECT=votre_projet
Utilisation
Surveillance des erreurs
// Dans un composant ou une API route
import * as Sentry from "@sentry/nextjs";
try {
// Opération risquée
} catch (error) {
Sentry.captureException(error);
}
Tracing distribué
// Dans une fonction API
import * as Sentry from "@sentry/nextjs";
export default async function handler(req, res) {
const transaction = Sentry.startTransaction({
op: "api.handler",
name: "Mon handler API",
});
try {
// Logique métier
} finally {
transaction.finish();
}
}
Relecture de session
// La relecture de session est configurée dans sentry.client.config.ts
// via l'intégration Sentry.Replay()
Journalisation
import * as Sentry from "@sentry/nextjs";
Sentry.captureMessage("Un événement personnalisé", {
level: "info",
extra: {
cle1: "valeur1",
cle2: "valeur2",
},
});
Profilage
// Ajoutez l'option tracesSampleRate dans la configuration
// et utilisez le profilage avec ProfilingIntegration
import { ProfilingIntegration } from "@sentry/profiling-node";
Sentry.init({
dsn: "VOTRE_DSN_SENTRY",
integrations: [
new ProfilingIntegration(),
],
profilesSampleRate: 1.0,
});
Surveillance IA
// Utilisez Sentry pour surveiller les appels à l'IA
// À configurer selon le fournisseur d'IA spécifique
Crons (Tâches planifiées)
import { SentryCron } from "@sentry/nextjs/crons";
// Nouveau cron
const cron = new SentryCron({
name: "Mon Cron",
schedule: "0 * * * *",
timeZone: "Europe/Paris",
});
cron.start();
Dépannage
Erreurs courantes
SENTRY_DSNmanquant : Assurez-vous que la variable d'environnementSENTRY_DSNest définie.- Problèmes de source maps : Vérifiez la configuration de
withSentryConfigdansnext.config.js. - Rendu côté client vs serveur : Assurez-vous de configurer séparément les configurations serveur et client.