1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-04-26 06:45:23 -04:00

sentry instrumentation

This commit is contained in:
Jake Jarvis 2025-03-29 20:37:28 -04:00
parent 4f5bc129b6
commit 87a24a98f0
Signed by: jake
SSH Key Fingerprint: SHA256:nCkvAjYA6XaSPUqc4TfbBQTpzr8Xj7ritg/sGInCdkc
21 changed files with 2244 additions and 333 deletions

View File

@ -23,7 +23,7 @@ CODE ARCHITECTURE:
│ ├── config/ # Configuration constants
│ ├── helpers/ # Utility functions
├── notes/ # Blog posts in markdown/MDX format
└── static/ # Static files such as images and videos
└── public/ # Static files
2. Component Organization:
- Keep reusable components in ./components/.

View File

@ -3,6 +3,7 @@
import { headers } from "next/headers";
import { z } from "zod";
import { Resend } from "resend";
import * as Sentry from "@sentry/nextjs";
import * as config from "../../lib/config";
const schema = z.object({
@ -22,6 +23,14 @@ export const sendMessage = async (
errors?: z.inferFormattedError<typeof schema>;
payload?: FormData;
}> => {
return await Sentry.withServerActionInstrumentation(
"sendMessage",
{
formData,
headers: headers(),
recordResponse: true,
},
async () => {
try {
const validatedFields = schema.safeParse(Object.fromEntries(formData));
@ -77,8 +86,10 @@ export const sendMessage = async (
subject: `[${config.siteName}] Contact Form Submission`,
text: validatedFields.data.message,
});
return { success: true, message: "Thanks! You should hear from me soon.", payload: formData };
} catch (error) {
console.error("[contact form] fatal error:", error);
Sentry.captureException(error);
return {
success: false,
@ -87,6 +98,6 @@ export const sendMessage = async (
payload: formData,
};
}
return { success: true, message: "Thanks! You should hear from me soon.", payload: formData };
}
);
};

View File

@ -2,7 +2,6 @@ import PageTitle from "../../components/PageTitle";
import Link from "../../components/Link";
import ContactForm from "./form";
import { addMetadata } from "../../lib/helpers/metadata";
import type { Route } from "next";
export const metadata = addMetadata({
title: "Contact Me",
@ -29,7 +28,7 @@ const Page = () => {
</p>
<p>
🔐 You can grab my public key here:{" "}
<Link href={"/pubkey.asc" as Route} title="My Public PGP Key" rel="pgpkey authn" openInNewTab>
<Link href="/pubkey.asc" title="My Public PGP Key" rel="pgpkey authn" openInNewTab>
<code style={{ fontSize: "0.925em", letterSpacing: "0.075em", wordSpacing: "-0.3em" }}>
6BF3 79D3 6F67 1480 2B0C 9CF2 51E6 9A39
</code>

14
app/error.tsx Normal file
View File

@ -0,0 +1,14 @@
"use client";
import { useEffect } from "react";
import * as Sentry from "@sentry/nextjs";
const Error = ({ error }: { error: Error & { digest?: string } }) => {
useEffect(() => {
Sentry.captureException(error);
}, [error]);
return <span>Something went very wrong! 😳</span>;
};
export default Error;

25
app/global-error.tsx Normal file
View File

@ -0,0 +1,25 @@
"use client";
import { useEffect } from "react";
import NextError from "next/error";
import * as Sentry from "@sentry/nextjs";
const GlobalError = ({ error }: { error: Error & { digest?: string } }) => {
useEffect(() => {
Sentry.captureException(error);
}, [error]);
return (
<html>
<body>
{/* `NextError` is the default Next.js error page component. Its type
definition requires a `statusCode` prop. However, since the App Router
does not expose status codes for errors, we simply pass 0 to render a
generic error message. */}
<NextError statusCode={0} />
</body>
</html>
);
};
export default GlobalError;

View File

@ -1,4 +1,5 @@
import { connection } from "next/server";
import * as Sentry from "@sentry/nextjs";
import commaNumber from "comma-number";
import CountUp from "../../../components/CountUp";
import redis from "../../../lib/helpers/redis";
@ -21,9 +22,7 @@ const HitCounter = async ({ slug }: { slug: string }) => {
</span>
);
} catch (error) {
console.error("[hit counter] fatal error:", error);
throw new Error();
Sentry.captureException(error);
}
};

View File

@ -1,5 +1,4 @@
import { Suspense } from "react";
import { ErrorBoundary } from "react-error-boundary";
import { JsonLd } from "react-schemaorg";
import { CalendarIcon, TagIcon, SquarePenIcon, EyeIcon } from "lucide-react";
import Link from "../../../components/Link";
@ -10,8 +9,8 @@ import HitCounter from "./counter";
import { getSlugs, getFrontMatter } from "../../../lib/helpers/posts";
import { addMetadata } from "../../../lib/helpers/metadata";
import * as config from "../../../lib/config";
import { BASE_URL } from "../../../lib/config/constants";
import type { Metadata, Route } from "next";
import { BASE_URL, POSTS_DIR } from "../../../lib/config/constants";
import type { Metadata } from "next";
import type { Article } from "schema-dts";
import styles from "./page.module.css";
@ -50,7 +49,7 @@ export const generateMetadata = async ({ params }: { params: Promise<{ slug: str
card: "summary_large_image",
},
alternates: {
canonical: `/notes/${slug}`,
canonical: `/${POSTS_DIR}/${slug}`,
},
});
};
@ -59,7 +58,7 @@ const Page = async ({ params }: { params: Promise<{ slug: string }> }) => {
const { slug } = await params;
const frontmatter = await getFrontMatter(slug);
const { default: MDXContent } = await import(`../../../notes/${slug}/index.mdx`);
const { default: MDXContent } = await import(`../../../${POSTS_DIR}/${slug}/index.mdx`);
return (
<>
@ -70,7 +69,7 @@ const Page = async ({ params }: { params: Promise<{ slug: string }> }) => {
headline: frontmatter!.title,
description: frontmatter!.description,
url: frontmatter!.permalink,
image: [`${BASE_URL}/notes/${slug}/opengraph-image`],
image: [`${BASE_URL}/${POSTS_DIR}/${frontmatter!.slug}/opengraph-image`],
keywords: frontmatter!.tags,
datePublished: frontmatter!.date,
dateModified: frontmatter!.date,
@ -85,7 +84,7 @@ const Page = async ({ params }: { params: Promise<{ slug: string }> }) => {
<div className={styles.meta}>
<div className={styles.metaItem}>
<Link href={`/notes/${frontmatter!.slug}` as Route} plain className={styles.metaLink}>
<Link href={`/${POSTS_DIR}/${frontmatter!.slug}`} plain className={styles.metaLink}>
<CalendarIcon size="1.2em" className={styles.metaIcon} />
<Time date={frontmatter!.date} format="MMMM d, y" />
</Link>
@ -106,7 +105,7 @@ const Page = async ({ params }: { params: Promise<{ slug: string }> }) => {
<div className={styles.metaItem}>
<Link
href={`https://github.com/${config.githubRepo}/blob/main/notes/${frontmatter!.slug}/index.mdx`}
href={`https://github.com/${config.githubRepo}/blob/main/${POSTS_DIR}/${frontmatter!.slug}/index.mdx`}
title={`Edit "${frontmatter!.title}" on GitHub`}
plain
className={styles.metaLink}
@ -118,7 +117,6 @@ const Page = async ({ params }: { params: Promise<{ slug: string }> }) => {
{/* only count hits on production site */}
{process.env.NEXT_PUBLIC_VERCEL_ENV !== "development" && process.env.NODE_ENV !== "development" ? (
<ErrorBoundary fallback={null}>
<div
className={styles.metaItem}
style={{
@ -133,16 +131,15 @@ const Page = async ({ params }: { params: Promise<{ slug: string }> }) => {
// show a zero here as a "loading indicator"
fallback={<span>0</span>}
>
<HitCounter slug={`notes/${frontmatter!.slug}`} />
<HitCounter slug={`${POSTS_DIR}/${frontmatter!.slug}`} />
</Suspense>
</div>
</ErrorBoundary>
) : null}
</div>
<h1 className={styles.title}>
<Link
href={`/notes/${frontmatter!.slug}` as Route}
href={`/${POSTS_DIR}/${frontmatter!.slug}`}
dangerouslySetInnerHTML={{ __html: frontmatter!.htmlTitle || frontmatter!.title }}
plain
className={styles.link}

View File

@ -3,8 +3,8 @@ import Time from "../../components/Time";
import { getFrontMatter } from "../../lib/helpers/posts";
import { addMetadata } from "../../lib/helpers/metadata";
import * as config from "../../lib/config";
import { POSTS_DIR } from "../../lib/config/constants";
import type { ReactElement } from "react";
import type { Route } from "next";
import type { FrontMatter } from "../../lib/helpers/posts";
import styles from "./page.module.css";
@ -13,25 +13,25 @@ export const metadata = addMetadata({
title: "Notes",
description: `Recent posts by ${config.authorName}.`,
alternates: {
canonical: "/notes",
canonical: `/${POSTS_DIR}`,
},
});
const Page = async () => {
// parse the year of each note and group them together
const notes = await getFrontMatter();
const notesByYear: {
// parse the year of each post and group them together
const posts = await getFrontMatter();
const postsByYear: {
[year: string]: FrontMatter[];
} = {};
notes.forEach((note) => {
const year = new Date(note.date).getUTCFullYear();
(notesByYear[year] || (notesByYear[year] = [])).push(note);
posts.forEach((post) => {
const year = new Date(post.date).getUTCFullYear();
(postsByYear[year] || (postsByYear[year] = [])).push(post);
});
const sections: ReactElement[] = [];
Object.entries(notesByYear).forEach(([year, posts]) => {
Object.entries(postsByYear).forEach(([year, posts]) => {
sections.push(
<section className={styles.section} key={year}>
<h2 className={styles.year}>{year}</h2>
@ -40,7 +40,7 @@ const Page = async () => {
<li className={styles.post} key={slug}>
<Time date={date} format="MMM d" className={styles.postDate} />
<span>
<Link href={`/notes/${slug}` as Route} dangerouslySetInnerHTML={{ __html: htmlTitle || title }} />
<Link href={`/${POSTS_DIR}/${slug}`} dangerouslySetInnerHTML={{ __html: htmlTitle || title }} />
</span>
</li>
))}

View File

@ -3,7 +3,6 @@ import { rgba } from "polished";
import { LockIcon } from "lucide-react";
import UnstyledLink from "../components/Link";
import type { ComponentPropsWithoutRef } from "react";
import type { Route } from "next";
import styles from "./page.module.css";
@ -149,7 +148,7 @@ const Page = () => {
</Link>{" "}
and{" "}
<Link
href={"/notes/my-first-code" as Route}
href="/notes/my-first-code"
title="Jake's Bulletin Board, circa 2003"
lightColor="#9932cc"
darkColor="#d588fb"
@ -259,7 +258,7 @@ const Page = () => {
</Link>{" "}
<sup>
<Link
href={"/pubkey.asc" as Route}
href="/pubkey.asc"
rel="pgpkey authn"
title="My Public Key"
lightColor="#757575"

View File

@ -7,7 +7,7 @@ const robots = (): MetadataRoute.Robots => ({
rules: [
{
userAgent: "*",
disallow: ["/_stream/", "/api/", "/stats/", "/tweets/", "/404", "/500"],
disallow: ["/_stream/", "/_otel/", "/api/", "/404", "/500"],
},
],
sitemap: `${BASE_URL}/sitemap.xml`,

View File

@ -1,6 +1,5 @@
import clsx from "clsx";
import Link from "../Link";
import type { Route } from "next";
import type { ComponentPropsWithoutRef } from "react";
import type { LucideIcon } from "lucide-react";
@ -8,7 +7,7 @@ import styles from "./MenuItem.module.css";
export type MenuItemProps = Omit<ComponentPropsWithoutRef<typeof Link>, "href"> & {
text?: string;
href?: Route;
href?: string;
icon?: LucideIcon;
current?: boolean;
};

View File

@ -1,7 +1,6 @@
import clsx from "clsx";
import Link from "../Link";
import type { ComponentPropsWithoutRef } from "react";
import type { Route } from "next";
import styles from "./PageTitle.module.css";
@ -12,7 +11,7 @@ export type PageTitleProps = ComponentPropsWithoutRef<"h1"> & {
const PageTitle = ({ canonical, className, children, ...rest }: PageTitleProps) => {
return (
<h1 className={clsx(styles.title, className)} {...rest}>
<Link href={canonical as Route} plain className={styles.slug}>
<Link href={canonical} plain className={styles.slug}>
{children}
</Link>
</h1>

29
instrumentation-client.ts Normal file
View File

@ -0,0 +1,29 @@
// This file configures the initialization of Sentry on the client.
// The added config here will be used whenever a users loads a page in their browser.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN || process.env.SENTRY_DSN,
integrations: [
Sentry.replayIntegration({
networkDetailAllowUrls: [process.env.NEXT_PUBLIC_VERCEL_PROJECT_PRODUCTION_URL!],
networkRequestHeaders: ["referer", "origin", "user-agent", "x-upstream-proxy"],
networkResponseHeaders: [
"location",
"x-matched-path",
"x-nextjs-prerender",
"x-vercel-cache",
"x-vercel-id",
"x-vercel-error",
"x-rewrite-url",
"x-got-milk",
],
}),
],
tracesSampleRate: 1.0,
replaysSessionSampleRate: 0,
replaysOnErrorSampleRate: 1.0,
debug: false,
});

13
instrumentation.ts Normal file
View File

@ -0,0 +1,13 @@
import * as Sentry from "@sentry/nextjs";
export const onRequestError = Sentry.captureRequestError;
export const register = async () => {
if (process.env.NEXT_RUNTIME === "nodejs") {
await import("./sentry.server.config");
}
if (process.env.NEXT_RUNTIME === "edge") {
await import("./sentry.edge.config");
}
};

View File

@ -36,17 +36,7 @@ export const middleware = (request: NextRequest) => {
// search the rewrite map for the short code
const proxiedOrigin = rewrites.get(key);
// return a 400 error if a rewrite was requested but the short code isn't found
if (!proxiedOrigin) {
return NextResponse.json(
{ error: "Unknown proxy key" },
{
status: 400,
headers,
}
);
}
if (proxiedOrigin) {
// it's now safe to build the rewritten URL
const proxiedPath = slashIndex === -1 ? "/" : pathAfterPrefix.slice(slashIndex);
const proxiedUrl = new URL(`${proxiedPath}${request.nextUrl.search}`, proxiedOrigin);
@ -59,6 +49,7 @@ export const middleware = (request: NextRequest) => {
headers,
});
}
}
// if we've gotten this far, continue normally to next.js
return NextResponse.next({
@ -70,6 +61,6 @@ export const middleware = (request: NextRequest) => {
export const config: MiddlewareConfig = {
// save compute time by skipping middleware for next.js internals and static files
matcher: [
"/((?!_next/|_vercel/|api/|\\.well-known/|[^?]*\\.(?:png|jpe?g|gif|webp|avif|svg|ico|webm|mp4|ttf|woff2?|xml|atom|txt|pdf|webmanifest)).*)",
"/((?!_next/static|_next/image|_vercel|_otel|api|\\.well-known|[^?]*\\.(?:png|jpe?g|gif|webp|avif|svg|ico|webm|mp4|ttf|woff2?|xml|atom|txt|pdf|webmanifest)).*)",
],
};

View File

@ -1,9 +1,15 @@
/* eslint-disable @typescript-eslint/no-require-imports */
import path from "path";
import type { NextConfig } from "next";
import withBundleAnalyzer from "@next/bundle-analyzer";
import withMDX from "@next/mdx";
import { visit } from "unist-util-visit";
import * as mdxPlugins from "./lib/helpers/remark-rehype-plugins";
import type { NextConfig } from "next";
type NextPlugin = (
config: NextConfig,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options?: any
) => NextConfig;
const nextConfig: NextConfig = {
reactStrictMode: true,
@ -143,11 +149,13 @@ const nextConfig: NextConfig = {
],
};
const nextPlugins = [
withBundleAnalyzer({
enabled: process.env.ANALYZE === "true",
// my own macgyvered version of next-compose-plugins (RIP)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const nextPlugins: Array<NextPlugin | [NextPlugin, any]> = [
require("@next/bundle-analyzer")({
enabled: !!process.env.ANALYZE,
}),
withMDX({
require("@next/mdx")({
options: {
remarkPlugins: [
mdxPlugins.remarkFrontmatter,
@ -156,7 +164,8 @@ const nextPlugins = [
mdxPlugins.remarkSmartypants,
// workaround for rehype-mdx-import-media not applying to `<video>` tags:
// https://github.com/Chailotl/remark-videos/blob/851c332993210e6f091453f7ed887be24492bcee/index.js
() => (tree) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
() => (tree: any) => {
visit(tree, "image", (node) => {
if (node.url.match(/\.(mp4|webm)$/i)) {
node.type = "element";
@ -191,10 +200,31 @@ const nextPlugins = [
],
},
}),
[
require("@sentry/nextjs").withSentryConfig,
{
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/build/
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
authToken: process.env.SENTRY_AUTH_TOKEN,
silent: !process.env.CI,
tunnelRoute: "/_otel", // ensure this path is included in middleware's negative config.matcher expression
widenClientFileUpload: true,
disableLogger: true,
telemetry: false,
bundleSizeOptimizations: {
excludeDebugStatements: true,
},
},
],
];
// my own macgyvered version of next-compose-plugins (RIP)
// eslint-disable-next-line import/no-anonymous-default-export
export default () => {
return nextPlugins.reduce((acc, plugin) => plugin(acc), { ...nextConfig });
};
export default (): NextConfig =>
nextPlugins.reduce((acc, next) => {
if (Array.isArray(next)) {
return (next[0] as NextPlugin)(acc, next[1]);
}
return (next as NextPlugin)(acc);
}, nextConfig);

View File

@ -23,11 +23,12 @@
"@giscus/react": "^3.1.0",
"@mdx-js/loader": "^3.1.0",
"@mdx-js/react": "^3.1.0",
"@next/bundle-analyzer": "15.3.0-canary.24",
"@next/mdx": "15.3.0-canary.24",
"@next/third-parties": "15.3.0-canary.24",
"@next/bundle-analyzer": "15.3.0-canary.25",
"@next/mdx": "15.3.0-canary.25",
"@next/third-parties": "15.3.0-canary.25",
"@octokit/graphql": "^8.2.1",
"@octokit/graphql-schema": "^15.26.0",
"@sentry/nextjs": "^9.10.1",
"@upstash/redis": "^1.34.6",
"clsx": "^2.1.1",
"comma-number": "^2.1.0",
@ -39,14 +40,13 @@
"html-entities": "^2.5.5",
"lucide-react": "0.485.0",
"modern-normalize": "^3.0.1",
"next": "15.3.0-canary.24",
"next": "15.3.0-canary.25",
"obj-str": "^1.1.0",
"polished": "^4.3.1",
"prop-types": "^15.8.1",
"react": "19.1.0",
"react-countup": "^6.5.3",
"react-dom": "19.1.0",
"react-error-boundary": "^5.0.0",
"react-innertext": "^1.1.5",
"react-is": "19.1.0",
"react-schemaorg": "^2.0.0",
@ -85,7 +85,7 @@
"babel-plugin-react-compiler": "19.0.0-beta-aeaed83-20250323",
"cross-env": "^7.0.3",
"eslint": "^9.23.0",
"eslint-config-next": "15.3.0-canary.24",
"eslint-config-next": "15.3.0-canary.25",
"eslint-config-prettier": "^10.1.1",
"eslint-plugin-css-modules": "^2.12.0",
"eslint-plugin-import": "^2.31.0",
@ -130,6 +130,7 @@
},
"pnpm": {
"onlyBuiltDependencies": [
"@sentry/cli",
"sharp",
"simple-git-hooks"
],

2137
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -34,6 +34,7 @@
- Giscus
- Resend
- Umami
- Sentry
- ...and more: https://jarv.is/uses
# VIEW SOURCE

12
sentry.edge.config.ts Normal file
View File

@ -0,0 +1,12 @@
// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on).
// The config you add here will be used whenever one of the edge features is loaded.
// Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN || process.env.SENTRY_DSN,
tracesSampleRate: 1.0,
debug: false,
});

11
sentry.server.config.ts Normal file
View File

@ -0,0 +1,11 @@
// This file configures the initialization of Sentry on the server.
// The config you add here will be used whenever the server handles a request.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN || process.env.SENTRY_DSN,
tracesSampleRate: 1.0,
debug: false,
});