Next.js course ยท Module 1: Next.js Configuration
Instrumentation and Application Debugging
In this lesson9
In Quantum Metropolis, advanced diagnostic systems are crucial for the proper functioning of the entire infrastructure. Networks of sensors and analyzers, invisible to the average citizen, constantly monitor every aspect of city systems, allowing engineers to quickly detect and fix problems. Similarly in the world of Next.js, instrumentation and debugging tools give developers insight into how applications work and the ability to quickly resolve issues.
What is Instrumentation in Next.js?
Instrumentation in the context of Next.js refers to the process of adding monitoring code to an application to collect data about its performance, errors, and behavior. It's like a network of quantum sensors placed at key points in Quantum Metropolis - they allow monitoring system status and collecting data necessary for analyzing their operation.
Next.js 16 offers advanced instrumentation tools that allow developers to better understand and optimize their application's behavior.
Configuring Instrumentation in Next.js 16
In Next.js 16, this is the job of the instrumentation.ts file, stable since Next.js 15, which runs once when the server starts. You can use it to configure monitoring tools such as Sentry, New Relic, or OpenTelemetry.
To enable instrumentation in a Next.js application, follow these steps:
Create a file named
instrumentation.ts(orinstrumentation.js) in the root directory of the application (alongsideapporsrc/app).Do not add any flag to
next.config. In Next.js 13 and 14 instrumentation was experimental and required theexperimental.instrumentationHooksetting, but since Next.js 15 it is stable, so in Next.js 16 the file alone is enough. You may still come across the old configuration in older projects:// next.config.js - Next.js 13 and 14 only, not needed in Next.js 16 /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { instrumentationHook: true, } }; module.exports = nextConfig;Implement the
registerhook in the instrumentation file:// instrumentation.ts export async function register() { if (process.env.NEXT_RUNTIME === 'nodejs') { // Code executed only in the Node.js runtime (not in the Edge Runtime) console.log('Initializing Quantum Metropolis monitoring system...'); // Here you can implement actual instrumentation // e.g., initializing Sentry, LogRocket, or OpenTelemetry } }
The register function is called at application startup and can be used to set up monitoring at the application level.
Integration with Popular Monitoring Tools
In Quantum Metropolis, different monitoring systems serve different roles - from monitoring energy levels to tracking citizen movement. Similarly in the web development world, different tools serve different monitoring purposes.
1. OpenTelemetry
OpenTelemetry is a set of APIs, libraries, and tools for collecting telemetry data (metrics, logs, and traces) from applications.
// instrumentation.ts
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
// Dynamic import to avoid issues during application building
const { registerOTel } = await import('./monitoring/otel');
registerOTel();
}
}
// monitoring/otel.ts
import * as opentelemetry from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
export function registerOTel() {
const sdk = new opentelemetry.NodeSDK({
// The exporter reads the collector address from OTEL_EXPORTER_OTLP_ENDPOINT and appends /v1/traces itself
traceExporter: new OTLPTraceExporter(),
instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();
console.log('OpenTelemetry has been initialized');
}2. Sentry
Sentry is a popular error monitoring platform that allows tracking, prioritizing, and fixing errors in real time.
// instrumentation.ts
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
const { initSentry } = await import('./monitoring/sentry');
initSentry();
}
}
// monitoring/sentry.ts
import * as Sentry from '@sentry/nextjs';
export function initSentry() {
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV,
tracesSampleRate: 1.0,
});
console.log('Sentry has been initialized');
}3. Custom Analytics
You can also implement your own analytics solution:
// instrumentation.ts
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
const { initAnalytics } = await import('./monitoring/analytics');
initAnalytics();
}
}
// monitoring/analytics.ts
import { NextRequest } from 'next/server';
// Middleware for collecting analytics data
export async function analyticsMiddleware(req: NextRequest, handler: () => Promise<Response>) {
const start = Date.now();
// Handle the request and measure how long it took
const response = await handler();
const responseTime = Date.now() - start;
// Record performance data
console.log(`Path: ${req.nextUrl.pathname}, Time: ${responseTime}ms`);
// In a real application, you would send this data to an analytics system
return response;
}
export function initAnalytics() {
console.log('Quantum Metropolis analytics system has been initialized');
}Client-Side Instrumentation
Instrumentation is not limited to the server. In client components, you can use various tools to monitor user experience and application performance.
React Profiler
React Profiler is a built-in React tool for measuring component rendering time. You can use it to identify performance bottlenecks in your application.
// components/PerformanceWrapper.tsx
"use client";
import { Profiler, ProfilerOnRenderCallback, ReactNode } from 'react';
interface PerformanceWrapperProps {
id: string;
children: ReactNode;
}
export function PerformanceWrapper({ id, children }: PerformanceWrapperProps) {
const handleRender: ProfilerOnRenderCallback = (
id, // id of the component that was rendered
phase, // "mount", "update" or "nested-update"
actualDuration, // time spent rendering
baseDuration, // estimated rendering time without optimizations
startTime, // when React started rendering
commitTime // when React finished rendering
) => {
// Record performance data
console.log(`[Profiler] ${id} - ${phase}: ${actualDuration.toFixed(2)}ms`);
// Note: a regular production build disables the Profiler, so onRender is not called here
// (you need a profiling build: next build --profile)
if (process.env.NODE_ENV === 'production') {
// sendToAnalytics({ id, phase, actualDuration, baseDuration });
}
};
return (
<Profiler id={id} onRender={handleRender}>
{children}
</Profiler>
);
}Now you can wrap any component in PerformanceWrapper to measure its performance:
// app/dashboard/page.tsx
"use client";
import { PerformanceWrapper } from '@/components/PerformanceWrapper';
import { DashboardContent } from '@/components/DashboardContent';
export default function DashboardPage() {
return (
<PerformanceWrapper id="dashboard-page">
<DashboardContent />
</PerformanceWrapper>
);
}Web Vitals
Web Vitals is a Google initiative aimed at providing unified guidance on quality metrics essential for delivering a great user experience on the web.
Next.js 16 makes it easy to report Web Vitals:
// app/_components/web-vitals.tsx
"use client";
import { useReportWebVitals } from 'next/web-vitals';
export function WebVitalsReporter() {
useReportWebVitals((metric) => {
const { id, name, rating, value } = metric;
// Record Web Vitals data
console.log(`[Web Vitals] ${name} (${rating}): ${value}`);
// In production, you would send this data to an analytics system
if (process.env.NODE_ENV === 'production') {
// sendToAnalytics({ id, name, rating, value });
}
});
return null;
}The root layout stays a Server Component and only imports this small client component:
// app/layout.tsx
import { WebVitalsReporter } from './_components/web-vitals';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<WebVitalsReporter />
{children}
</body>
</html>
);
}The rating field is good, needs-improvement or poor, a ready-made assessment of the metric against Google's thresholds.
Debugging Next.js 16 Applications
In Quantum Metropolis, engineers use advanced diagnostic tools to identify and fix problems in city systems. Similarly, Next.js developers have access to a range of tools that facilitate application debugging.
1. Server-Side Debugging
a) Server Logs
The simplest way to debug on the server is by adding logs:
// app/api/users/route.ts
export async function GET() {
console.log('Starting to fetch users...');
try {
const users = await fetchUsers();
console.log(`Fetched ${users.length} users`);
return Response.json(users);
} catch (error) {
console.error('Error fetching users:', error);
return Response.json({ error: 'Internal Server Error' }, { status: 500 });
}
}These logs will be visible in the server console where the Next.js application is running.
b) Debugging with Node Inspector
Next.js supports the built-in Node.js debugger. Since Next.js 16.1, you just add the --inspect flag to next dev (previously you used the NODE_OPTIONS='--inspect' variable, which attached the debugger to every process started by Next.js):
npx next dev --inspectThen open Chrome and navigate to chrome://inspect, where you can connect to the Node.js process and use Chrome developer tools for debugging.
You can also add breakpoints in code using the debugger statement:
// app/api/data/route.ts
export async function GET() {
debugger; // Will pause execution when debugger is attached
const data = await processData();
return Response.json(data);
}2. Client-Side Debugging
a) React Developer Tools
React Developer Tools is a browser extension that allows inspecting the React component tree, monitoring props, state, and hooks.
To effectively debug with React Developer Tools:
- Install the extension in your browser (Chrome, Firefox)
- Open the browser developer tools and go to the "Components" or "Profiler" tab
- Examine the component structure and their properties
Particularly useful when debugging Server and Client Components are the labels next to component names:
- Server Components have a badge with their environment next to the name (e.g. "Server")
- Client Components are shown without such a badge
b) Debugging State with React DevTools
// components/UserProfile.tsx
"use client";
import { useState, useEffect } from 'react';
export default function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchUser() {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) throw new Error('Failed to fetch user');
const data = await response.json();
setUser(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchUser();
}, [userId]);
if (loading) return <div>Loading user data...</div>;
if (error) return <div>Error: {error}</div>;
if (!user) return <div>No user found</div>;
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}In React DevTools, you can monitor changes to the user, loading, and error states in real time.
3. Debugging Server Actions
Server Actions, stable since Next.js 14, allow executing code on the server from client components. Debugging them requires a special approach:
// app/actions.ts
"use server";
import { revalidatePath } from 'next/cache';
export async function updateUserProfile(formData: FormData) {
const userId = formData.get('userId');
const name = formData.get('name');
const email = formData.get('email');
console.log(`Updating profile for user ${userId}:`, { name, email });
try {
// Profile update logic
const result = await updateUserInDatabase(userId, { name, email });
console.log('Update result:', result);
// Refresh the path to show updated data
revalidatePath(`/users/${userId}`);
return { success: true };
} catch (error) {
console.error('Error updating profile:', error);
return { success: false, error: error.message };
}
}Debugging Server Actions mainly involves:
- Adding server logs
- Checking that data passed from the form is correct
- Monitoring responses returned to client components
Since Next.js 16.2, the development server does part of this work for you: every time a Server Function runs, it prints its name, arguments, execution time and the file it is defined in to the terminal.
4. Built-in Next.js 16 Tools
Next.js 16 includes several built-in tools that make debugging easier:
a) Advanced Error Messages
Next.js 16 displays detailed error messages in the developer interface, pointing exactly where the problem occurred and suggesting solutions.
b) Fast Refresh
Fast Refresh allows preserving component state while making code changes, which greatly facilitates debugging and iterative development.
c) Next.js DevTools
In development mode, Next.js 16 shows the Next.js Dev Tools indicator in a corner of the page. It works without any configuration: it reports compile and runtime errors, shows whether the current route is static or dynamic, and opens a panel with more details. You can move it with the devIndicators option, and the Next.js DevTools MCP server gives AI coding agents the same information.
If you want Web Vitals reports to point at the element responsible for a problem (for example the LCP image or the element that shifted the layout), enable the experimental webVitalsAttribution option:
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
webVitalsAttribution: ['CLS', 'LCP'],
},
};
module.exports = nextConfig;The option is experimental, so turn it on only while you hunt for a problem; the Dev Tools indicator itself works without it.
Application Performance Monitoring
In Quantum Metropolis, engineers constantly monitor the performance of all systems to ensure an optimal experience for residents. In the world of Next.js, performance monitoring is equally important for ensuring a good user experience.
1. Next.js Analytics
Next.js offers a built-in tool for monitoring Web Vitals that can be integrated with analytics tools:
// pages/_app.js - Pages Router only (in the App Router use the useReportWebVitals hook shown above)
export function reportWebVitals(metric) {
const { id, name, label, value } = metric;
// Example: sending metrics to Google Analytics 4
window.gtag('event', name, {
value: Math.round(name === 'CLS' ? value * 1000 : value), // CLS values are typically small
event_label: id,
non_interaction: true,
});
}2. Custom Performance Monitoring
You can also implement your own performance monitoring using the Performance API:
// lib/performance.ts
export function measurePageLoad() {
if (typeof window !== 'undefined' && window.performance) {
const performanceEntries = performance.getEntriesByType('navigation');
if (performanceEntries.length > 0) {
const navigationEntry = performanceEntries[0] as PerformanceNavigationTiming;
const metrics = {
// Time from navigation start to DOM completion
domComplete: navigationEntry.domComplete,
// Time from navigation start to full page load
loadComplete: navigationEntry.loadEventEnd,
// Time from navigation start to first render
firstPaint: performance.getEntriesByName('first-paint')[0]?.startTime || 0,
// Time from navigation start to first content render
firstContentfulPaint: performance.getEntriesByName('first-contentful-paint')[0]?.startTime || 0,
};
console.log('Performance Metrics:', metrics);
// In production, you would send this data to an analytics system
if (process.env.NODE_ENV === 'production') {
// sendToAnalytics(metrics);
}
}
}
}You can call this function in a client component, for example:
// components/PerformanceMonitor.tsx
"use client";
import { useEffect } from 'react';
import { measurePageLoad } from '@/lib/performance';
export function PerformanceMonitor() {
useEffect(() => {
// Measure performance after page load
if (document.readyState === 'complete') {
measurePageLoad();
} else {
// loadEventEnd is only known after the load event handlers finish
const onLoad = () => setTimeout(measurePageLoad, 0);
window.addEventListener('load', onLoad);
return () => window.removeEventListener('load', onLoad);
}
}, []);
return null; // Component doesn't render anything visible
}Diagnosing Server and Client Component Issues
One of the most advanced aspects of Next.js 16 is the Server and Client Components system. However, this introduces new debugging challenges.
1. Common Server Component Problems
a) Attempting to use a React hook in a Server Component
// app/dashboard/page.tsx
export default function Dashboard() {
// ERROR: Cannot use hooks in Server Components
const [count, setCount] = useState(0);
return <div>Dashboard</div>;
}Solution: Move state logic to a Client Component.
// app/dashboard/page.tsx
import { DashboardClient } from './dashboard-client';
export default function Dashboard() {
// Server Component
return <DashboardClient />;
}
// dashboard-client.tsx
"use client";
import { useState } from 'react';
export function DashboardClient() {
// Now we can use a React hook
const [count, setCount] = useState(0);
return <div>Dashboard Count: {count}</div>;
}b) Attempting to access browser APIs in a Server Component
// app/dashboard/page.tsx
export default function Dashboard() {
// ERROR: there is no window object on the server (ReferenceError: window is not defined)
const windowWidth = window.innerWidth;
return <div>Width: {windowWidth}</div>;
}Solution: Move code using browser APIs to a Client Component.
// app/dashboard/page.tsx
import { WindowSizeClient } from './window-size-client';
export default function Dashboard() {
return <WindowSizeClient />;
}
// window-size-client.tsx
"use client";
import { useState, useEffect } from 'react';
export function WindowSizeClient() {
const [windowWidth, setWindowWidth] = useState(0);
useEffect(() => {
setWindowWidth(window.innerWidth);
const handleResize = () => setWindowWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return <div>Width: {windowWidth}</div>;
}2. Common Client Component Problems
a) Importing a Server Component into a Client Component
// ERROR: Cannot directly import a Server Component into a Client Component
// components/dashboard-wrapper.tsx
"use client";
import { ServerDataFetcher } from './server-data-fetcher';
export function DashboardWrapper() {
return (
<div className="dashboard">
<ServerDataFetcher /> {/* This won't work */}
</div>
);
}Solution: Pass Server Components as props to Client Components.
// app/dashboard/page.tsx
import { DashboardWrapper } from '@/components/dashboard-wrapper';
import { ServerDataFetcher } from '@/components/server-data-fetcher';
export default function Dashboard() {
return (
<DashboardWrapper>
<ServerDataFetcher /> {/* Passed as children */}
</DashboardWrapper>
);
}
// components/dashboard-wrapper.tsx
"use client";
export function DashboardWrapper({ children }) {
return (
<div className="dashboard">
{children}
</div>
);
}
// components/server-data-fetcher.tsx
// Server Component
export async function ServerDataFetcher() {
const data = await fetchData();
return <div>{data}</div>;
}External Tools for Production Monitoring
In Quantum Metropolis, central monitoring systems collect data from thousands of sensors distributed across the city, creating a complete picture of the city infrastructure's status. In the world of web applications, similar external tools help monitor production deployments.
1. Vercel Analytics
If you host your application on Vercel (the creators of Next.js), you can use Vercel Analytics:
npm install @vercel/analytics// app/layout.tsx
import { Analytics } from '@vercel/analytics/react';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
);
}2. New Relic
New Relic is a comprehensive application monitoring tool that allows tracking performance, errors, and user behavior.
npm install newrelicThen create a newrelic.js file in the project's root directory:
// newrelic.js
'use strict';
exports.config = {
app_name: ['Quantum Voyages - Next.js'],
license_key: process.env.NEW_RELIC_LICENSE_KEY,
logging: {
level: 'info'
},
allow_all_headers: true,
attributes: {
exclude: [
'request.headers.cookie',
'request.headers.authorization',
'request.headers.proxyAuthorization',
'request.headers.setCookie*',
'request.headers.x*',
'response.headers.cookie',
'response.headers.authorization',
'response.headers.proxyAuthorization',
'response.headers.setCookie*',
'response.headers.x*'
]
}
};3. Datadog
Datadog is a cloud monitoring platform that provides monitoring of servers, databases, tools, and services through a data analytics platform.
npm install @datadog/browser-rum// app/datadog-rum.tsx
"use client";
import { useEffect } from 'react';
import { datadogRum } from '@datadog/browser-rum';
export function DatadogRUM() {
useEffect(() => {
if (process.env.NODE_ENV === 'production') {
datadogRum.init({
applicationId: process.env.NEXT_PUBLIC_DATADOG_APPLICATION_ID,
clientToken: process.env.NEXT_PUBLIC_DATADOG_CLIENT_TOKEN,
site: 'datadoghq.eu', // or 'datadoghq.com' depending on region
service: 'quantum-voyages',
env: process.env.NODE_ENV,
version: '1.0.0',
sessionSampleRate: 100,
sessionReplaySampleRate: 100,
trackUserInteractions: true,
trackResources: true,
trackLongTasks: true,
defaultPrivacyLevel: 'mask-user-input'
});
}
}, []);
return null;
}Then add the component to the layout:
// app/layout.tsx
import { DatadogRUM } from './datadog-rum';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
{children}
<DatadogRUM />
</body>
</html>
);
}Summary
Instrumentation and debugging are crucial aspects of Next.js 16 application development, just as monitoring systems are essential for the proper functioning of Quantum Metropolis. With the right tools and practices, you can:
- Monitor performance of the application in production environments
- Track errors and fix them quickly
- Understand user behavior and optimize the experience
- Debug complex scenarios related to Server and Client Components
- Ensure reliability of the application as it grows
Remember that the best approach is to include instrumentation and monitoring early in the application development cycle, rather than adding them as an afterthought. Just as Quantum Metropolis engineers design monitoring systems simultaneously with building city infrastructure, you should implement debugging and monitoring tools at the early stages of your Next.js application development.
In the next lesson you will get to know the Next.js 16 developer tools; managing environment variables in the production configuration comes in module 8, which will allow for secure storage of sensitive data and customizing application behavior for different environments.
Code for this lesson: App.tsx
import React, { useState } from 'react';
interface LogEntry {
id: number;
timestamp: string;
level: 'info' | 'warn' | 'error';
system: string;
message: string;
}
const InstrumentationDashboard = () => {
const [logs, setLogs] = useState<LogEntry[]>([]);
const [filter, setFilter] = useState<string>('all');
const [otelEnabled, setOtelEnabled] = useState(false);
const [sentryEnabled, setSentryEnabled] = useState(false);
const addLog = (level: LogEntry['level'], system: string, message: string) => {
const entry: LogEntry = {
id: Date.now() + Math.random(),
timestamp: new Date().toISOString().slice(11, 23),
level,
system,
message,
};
setLogs(prev => [entry, ...prev].slice(0, 20));
};
const simulateRegister = () => {
addLog('info', 'instrumentation.ts', 'register() called - NEXT_RUNTIME=nodejs');
setTimeout(() => {
if (otelEnabled) addLog('info', 'OpenTelemetry', 'Trace exporter initialized');
if (sentryEnabled) addLog('info', 'Sentry', 'Error tracking enabled');
addLog('info', 'Server', 'Instrumentation hooks registered');
}, 500);
};
const simulateError = () => {
addLog('error', 'API Route', 'Unhandled exception in /api/users');
if (sentryEnabled) {
setTimeout(() => addLog('warn', 'Sentry', 'Error captured and sent to dashboard'), 300);
}
};
const simulateRequest = () => {
addLog('info', 'Middleware', 'Incoming request: GET /dashboard');
if (otelEnabled) {
addLog('info', 'OpenTelemetry', 'Span created: HTTP GET /dashboard');
setTimeout(() => addLog('info', 'OpenTelemetry', 'Span completed: 145ms'), 400);
}
setTimeout(() => addLog('info', 'Server', 'Response sent: 200 OK'), 600);
};
const levelColor = (level: string) => {
switch (level) {
case 'info': return '#4caf50';
case 'warn': return '#ff9800';
case 'error': return '#f44336';
default: return '#999';
}
};
const filteredLogs = filter === 'all' ? logs : logs.filter(l => l.level === filter);
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#fff', fontFamily: 'monospace' }}>
<h1 style={{ color: '#64ffda', textAlign: 'center', marginBottom: '8px' }}>
Instrumentation Dashboard
</h1>
<p style={{ textAlign: 'center', color: '#888', marginBottom: '24px' }}>
Metropolis Quantum - Monitoring System
</p>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', maxWidth: '900px', margin: '0 auto 20px' }}>
<div style={{ background: 'rgba(255,255,255,0.05)', padding: '16px', borderRadius: '10px', border: '1px solid #333' }}>
<h3 style={{ color: '#7c4dff', marginBottom: '12px' }}>Monitoring Tools</h3>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px', cursor: 'pointer' }}>
<input type="checkbox" checked={otelEnabled} onChange={() => setOtelEnabled(!otelEnabled)} />
<span style={{ color: otelEnabled ? '#4caf50' : '#666' }}>OpenTelemetry</span>
</label>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
<input type="checkbox" checked={sentryEnabled} onChange={() => setSentryEnabled(!sentryEnabled)} />
<span style={{ color: sentryEnabled ? '#4caf50' : '#666' }}>Sentry</span>
</label>
</div>
<div style={{ background: 'rgba(255,255,255,0.05)', padding: '16px', borderRadius: '10px', border: '1px solid #333' }}>
<h3 style={{ color: '#7c4dff', marginBottom: '12px' }}>Simulate</h3>
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
<button onClick={simulateRegister} style={{ padding: '8px', background: '#1a73e8', border: 'none', borderRadius: '6px', color: '#fff', cursor: 'pointer' }}>
register() Hook
</button>
<button onClick={simulateRequest} style={{ padding: '8px', background: '#0f9d58', border: 'none', borderRadius: '6px', color: '#fff', cursor: 'pointer' }}>
HTTP Request
</button>
<button onClick={simulateError} style={{ padding: '8px', background: '#db4437', border: 'none', borderRadius: '6px', color: '#fff', cursor: 'pointer' }}>
Trigger Error
</button>
</div>
</div>
</div>
<div style={{ maxWidth: '900px', margin: '0 auto' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
<h3 style={{ color: '#64ffda' }}>Event Log</h3>
<div style={{ display: 'flex', gap: '6px' }}>
{['all', 'info', 'warn', 'error'].map(f => (
<button key={f} onClick={() => setFilter(f)}
style={{ padding: '4px 12px', background: filter === f ? '#7c4dff' : 'rgba(255,255,255,0.1)',
border: 'none', borderRadius: '4px', color: '#fff', cursor: 'pointer', fontSize: '12px' }}>
{f.toUpperCase()}
</button>
))}
<button onClick={() => setLogs([])}
style={{ padding: '4px 12px', background: 'rgba(255,0,0,0.2)', border: 'none', borderRadius: '4px', color: '#f44336', cursor: 'pointer', fontSize: '12px' }}>
CLEAR
</button>
</div>
</div>
<div style={{ background: '#000', borderRadius: '8px', padding: '12px', minHeight: '200px', maxHeight: '300px', overflowY: 'auto' }}>
{filteredLogs.length === 0 ? (
<p style={{ color: '#555', textAlign: 'center', paddingTop: '80px' }}>
Enable tools and simulate events to see logs...
</p>
) : (
filteredLogs.map(log => (
<div key={log.id} style={{ padding: '4px 0', borderBottom: '1px solid #1a1a1a', fontSize: '13px' }}>
<span style={{ color: '#555' }}>{log.timestamp}</span>
{' '}
<span style={{ color: levelColor(log.level), fontWeight: 'bold' }}>[{log.level.toUpperCase()}]</span>
{' '}
<span style={{ color: '#7c4dff' }}>[{log.system}]</span>
{' '}
<span style={{ color: '#ccc' }}>{log.message}</span>
</div>
))
)}
</div>
</div>
</div>
);
};
export default InstrumentationDashboard;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which file in the Next.js root directory is executed at server startup to configure monitoring?
2. Which function do you implement in the instrumentation file to start monitoring at application startup?
3. What should you do when an error appears about using the useState hook in a Server Component?
Hands-on tasks in the game
- Click in order
Arrange the command that starts the development server with the Node.js debugger in Next.js 16.1+