Explain it simply
Explain it simply
Picture a shop on a busy street. The sign out front tells passers-by what it sells: that is your SEO metadata. The logbook behind the counter tells the owner what happened and when: those are your logs. A note of how long customers wait at the till is your Web Vitals.
Without all three, nobody finds the shop, nobody knows what happened when stock goes missing, and nobody knows why customers walk out.
Problem → Why → Solution
The problem: logging everything, finding nothing
Half an hour after a deploy, a user reports "I can't save notes". The logs hold hundreds of lines that just say "error", with no page and no release attached. Worse, a debug log writes the whole session object, including cookies and tokens, plus the full text of the user's note into the log service.
Now anyone with access to the logs can hijack user accounts and read private writing.
"use server";
export async function createNote(formData: FormData) {
const session = await getSession();
console.log("createNote", session, Object.fromEntries(formData)); // token + note body
try {
await db.note.create({ data: { title: String(formData.get("title")) } });
} catch (e) {
console.log("error"); // which page? which release? which error?
}
}Why are these logs useless and dangerous?
The first log prints secrets in plain text and ships them to everyone who can read the log service. The second log is the opposite: it lacks everything needed to debug, with no message, path or release. A good log carries exactly what you need to find the problem, and never a secret.
Core concept: three production feedback loops
Once you deploy, the app leaves your hands. You need three feedback loops to know what is happening, and each answers a different question.
| Loop | Question it answers | Next.js tools |
|---|---|---|
| SEO | Can search engines find and describe my pages? | Metadata API, sitemap.ts, robots.ts |
| Logs | What failed, where, and in which release? | Structured logs, instrumentation.ts |
| Real-user metrics | Is the app fast for real users? | useReportWebVitals or hosting analytics |
For SEO, every route needs a distinct title and description, a canonical URL and an Open Graph image for social sharing. The canonical URL tells search engines which address is the original when pages such as /notes?sort=new and /notes show the same content. app/sitemap.ts lists your public pages, and app/robots.ts advises crawlers which paths to crawl or skip.
The rule for logs is that machines must be able to parse them and humans must be able to understand them. Write each log line as one JSON object with a level, an event name, the release version, the path, a request ID and the error digest. Never include passwords, tokens, cookies, personal data such as emails, or content users wrote. In production, Next.js shows users a digest ID instead of the real error message, and you use that digest to find the matching server log.
The last loop is field data measured in real users' browsers. Lighthouse is a simulation on your machine; field data comes from real phones on real networks. Tag every metric with the release version and you can say precisely that "INP went up after Tuesday's deploy". The three loops reinforce each other: a slow LCP hurts both users and search ranking, and an error spike in the logs usually shows up in the vitals of the same release.
- Metadata and sitemap guide crawlers
- Tag every log with release and path
- Leave out secrets and personal data
- Compare Web Vitals across releases
For every log line ask two questions: what happens if this leaks, and will this help me find a bug at 2 a.m.?
General pattern: one structured log line
type Level = "info" | "warn" | "error";
export function log(level: Level, event: string, fields: Record<string, unknown>) {
console.log(JSON.stringify({
time: new Date().toISOString(),
level,
event,
release: process.env.APP_VERSION,
...fields, // ids, paths, durations: never tokens, cookies or user content
}));
}Each log line is one JSON object, so a log service can filter by field (for example level=error in a single release). The release is always included, so problems can be tied to a deploy.
Example: reporting Web Vitals from real users
The useReportWebVitals hook from next/web-vitals calls your callback each time the browser finishes measuring a metric. Because it is a hook, it only works in a Client Component. The Next.js docs show putting it in its own file and rendering it in the root layout, so the client boundary stays limited to this one small component.
"use client";
import { useReportWebVitals } from "next/web-vitals";
export function WebVitals() {
useReportWebVitals((metric) => {
navigator.sendBeacon(
"/api/vitals",
JSON.stringify({ name: metric.name, value: metric.value }),
);
});
return null;
}Code breakdown
- A client-only reporter
"use client";Only the browser can measure these metrics, so this must be a Client Component. It draws no UI, so it adds almost nothing to the page.
- One callback per metric
useReportWebVitals((metric) => {The metric object carries fields such as name (LCP, INP, CLS and so on), value, a unique id and a rating. The callback runs as each metric becomes ready.
- Fire and forget
navigator.sendBeacon(sendBeacon can deliver data even while the page is closing and does not wait for a response. That matters because metrics such as CLS and INP are often finalised as the user leaves. A string body arrives as text/plain.
- Send only what you need
JSON.stringify({ name: metric.name, value: metric.value }),Only the metric name and value are sent, with nothing about the user. In production, adding the page path and release version lets the dashboard split results by page and by release.
- Renders nothing
return null;The component exists only for its side effect. Add <WebVitals /> once in the root layout and every route reports its metrics.
The browser can send Web Vitals metrics to a monitoring endpoint.sitemap.ts and robots.ts
Put sitemap.ts in the app folder and return an array, and Next.js serves /sitemap.xml. You can loop over the public notes from the database and add one URL each. URLs must be absolute, starting with https://.
import type { MetadataRoute } from "next";
import { getPublicNotes } from "@/lib/notes";
const SITE = "https://notes.example.com";
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const notes = await getPublicNotes();
return [
{ url: SITE, lastModified: new Date() },
...notes.map((note) => ({
url: `${SITE}/notes/${note.slug}`,
lastModified: note.updatedAt,
})),
];
}import type { MetadataRoute } from "next";
export default function robots(): MetadataRoute.Robots {
return {
rules: { userAgent: "*", allow: "/", disallow: "/dashboard/" },
sitemap: "https://notes.example.com/sitemap.xml",
};
}robots.txt is not security
Disallow politely asks well-behaved crawlers to stay away; it blocks nobody. robots.txt is itself public, so anyone can read the paths you list. Protect the dashboard with authentication, and use robots: { index: false } in a page's metadata for pages that must stay out of search results.
Catching server errors in one place
An instrumentation.ts file in the project root (or src) runs once when the server starts. In Next.js 15 and later, exporting onRequestError from it gets called for errors thrown while rendering Server Components, in Route Handlers and in Server Actions. You report errors from one place instead of adding try/catch everywhere. Check your version's docs for the exact fields.
import type { Instrumentation } from "next";
type OnRequestError = Instrumentation.onRequestError;
export const onRequestError: OnRequestError = async (err, request, ctx) => {
console.error(JSON.stringify({
level: "error",
event: "request-error",
digest: (err as Error & { digest?: string }).digest,
message: (err as Error).message,
method: request.method,
route: ctx.routePath, // "/notes/[id]", not the real id or query string
release: process.env.APP_VERSION,
}));
};In real projects
In real projects
Production teams usually keep one dashboard that shows the error rate, the 75th percentile of LCP and INP, and deploy markers (vertical lines at the moment each release went out). When the error rate climbs right at a deploy marker, the decision to roll that release back takes minutes. Alerts use clear rules such as "error rate above 2% for five minutes".
On the SEO side, teams submit the sitemap to a tool such as Google Search Console and watch the number of indexed pages and any crawl errors. On the logging side, most companies set a retention period (for example 30 days) and restrict who can read logs. Finding personal data in logs is often treated as a privacy incident.
Common mistakes
Common mistakes
- Logging the whole session object, all request headers or the full form data while debugging. Cookies, tokens, emails and user content end up in the log service, where they are hard to remove. Pick only what you need, such as IDs and paths.
- Leaving the release version out of metrics and logs. You see a graph jump but cannot tell which deploy caused it, so deciding between a rollback and a database investigation becomes guesswork.
- Believing /dashboard is safe because robots.txt disallows it. That is only a request to crawlers; without authentication, anyone who knows the URL can open it.
- Serving many URLs with ?sort= and ?page= variations of the same content without a canonical URL. Search engines cannot tell which is the original, and ranking signals get split between them.
Mini challenge
Try it yourself: the /api/vitals endpoint
Write the POST handler for app/api/vitals/route.ts that receives what the example's WebVitals component sends. Validate the data with zod, rate the metric as good, needs-improvement or poor, and print one structured log line without secrets. Test it by calling the handler with real Request objects.
- Accept only LCP, INP and CLS as name; value must not be negative and path must start with /
- Return status 400 for invalid data and an empty 204 for valid data
- Thresholds: LCP 2500/4000 ms, INP 200/500 ms, CLS 0.1/0.25
- Include the release version in the log and strip the query string from the path
import { z } from "zod";
// TODO: a THRESHOLDS table for LCP, INP and CLS: [good, poor]
// TODO: a zod schema for { name, value, path }
export function rate(name: "LCP" | "INP" | "CLS", value: number) {
// TODO: "good" | "needs-improvement" | "poor"
}
export async function POST(request: Request): Promise<Response> {
// TODO: parse the JSON body safely (bad JSON must not crash the handler)
// TODO: 400 on invalid data
// TODO: log one JSON line: event, release, name, value, rating, path without "?..."
// TODO: 204 with no body
}
// TODO: call POST with a few new Request(...) objects and print each statusExpected: One JSON log line per metric (rated good, needs-improvement and poor), each followed by "-> 204", then "-> 400" with no log for the unsupported name FID. The INP log's path no longer contains ?email=....
Show hint
request.json() rejects on malformed JSON, so turn that into null with .catch(() => null) and pass it to schema.safeParse(); the single 400 path then covers both cases. For an empty response use new Response(null, { status: 204 }).
Show solution
import { z } from "zod";
const THRESHOLDS = { LCP: [2500, 4000], INP: [200, 500], CLS: [0.1, 0.25] } as const;
const VitalSchema = z.object({
name: z.enum(["LCP", "INP", "CLS"]),
value: z.number().nonnegative(),
path: z.string().startsWith("/").max(200),
});
export function rate(name: keyof typeof THRESHOLDS, value: number) {
const [good, poor] = THRESHOLDS[name];
return value <= good ? "good" : value <= poor ? "needs-improvement" : "poor";
}
export async function POST(request: Request): Promise<Response> {
const parsed = VitalSchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: "invalid metric" }, { status: 400 });
const { name, value, path } = parsed.data;
console.log(JSON.stringify({
level: "info",
event: "web-vital",
release: process.env.APP_VERSION ?? "dev",
name,
value,
rating: rate(name, value),
path: path.split("?")[0], // query strings can hold emails or tokens
}));
return new Response(null, { status: 204 });
}
// Demo: call the handler the way Next.js would, with real Request objects.
async function demo() {
process.env.APP_VERSION = "2026.11.09-a1b2c3d";
const bodies = [
{ name: "LCP", value: 1830, path: "/notes" },
{ name: "INP", value: 340, path: "/notes/42?email=mya@example.com" },
{ name: "CLS", value: 0.31, path: "/" },
{ name: "FID", value: 12, path: "/" },
];
for (const body of bodies) {
const request = new Request("http://localhost/api/vitals", {
method: "POST",
body: JSON.stringify(body),
});
const res = await POST(request);
console.log(`-> ${res.status}`);
}
}
demo();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Give every route a title, description and canonical URL, and guide crawlers with sitemap.ts and robots.ts
- robots.txt is not security; protect private pages with authentication
- Log JSON lines with release, route and digest, and leave out tokens, cookies and personal data
- Collect real users' LCP, INP and CLS with useReportWebVitals and compare them release by release
Next.js — Production Checklist — Next.js
Next.js — Production Checklist — Next.js