1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-07-03 14:06:40 -04:00

validate environment variables at build time

This commit is contained in:
2025-04-09 09:11:18 -04:00
parent 84702aeab1
commit eb92e54fd6
23 changed files with 150 additions and 60 deletions

View File

@ -1,11 +1,12 @@
import { env } from "../lib/env";
import Script from "next/script";
const Analytics = () => {
if (process.env.NEXT_PUBLIC_VERCEL_ENV !== "production") {
if (env.VERCEL_ENV !== "production") {
return null;
}
if (!process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID) {
if (!env.NEXT_PUBLIC_UMAMI_WEBSITE_ID) {
return null;
}
@ -14,8 +15,8 @@ const Analytics = () => {
src="/_stream/u/script.js" // see next.config.ts rewrite
id="umami-js"
strategy="afterInteractive"
data-website-id={process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID}
data-domains={process.env.NEXT_PUBLIC_VERCEL_PROJECT_PRODUCTION_URL}
data-website-id={env.NEXT_PUBLIC_UMAMI_WEBSITE_ID}
data-domains={env.VERCEL_PROJECT_PRODUCTION_URL}
/>
);
};

View File

@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { unstable_cache as cache } from "next/cache";
import redis from "../../../lib/helpers/redis";
import redis from "../../../lib/redis";
// cache response from the db
const getData = cache(

View File

@ -1,5 +1,6 @@
"use server";
import { env } from "../../lib/env";
import { headers } from "next/headers";
import * as v from "valibot";
import { Resend } from "resend";
@ -49,10 +50,6 @@ export const send = async (state: ContactState, payload: FormData): Promise<Cont
// TODO: remove after debugging why automated spam entries are causing 500 errors
console.debug("[contact form] received payload:", payload);
if (!process.env.RESEND_API_KEY) {
throw new Error("[contact form] 'RESEND_API_KEY' is not set.");
}
try {
const data = v.safeParse(ContactSchema, Object.fromEntries(payload));
@ -75,7 +72,7 @@ export const send = async (state: ContactState, payload: FormData): Promise<Cont
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
secret: process.env.TURNSTILE_SECRET_KEY || "1x0000000000000000000000000000000AA",
secret: env.TURNSTILE_SECRET_KEY || "1x0000000000000000000000000000000AA",
response: data.output["cf-turnstile-response"],
remoteip,
}),
@ -95,17 +92,17 @@ export const send = async (state: ContactState, payload: FormData): Promise<Cont
};
}
if (!process.env.RESEND_FROM_EMAIL) {
if (!env.RESEND_FROM_EMAIL) {
// https://resend.com/docs/api-reference/emails/send-email
console.warn("[contact form] 'RESEND_FROM_EMAIL' is not set, falling back to onboarding@resend.dev.");
}
// send email
const resend = new Resend(process.env.RESEND_API_KEY!);
const resend = new Resend(env.RESEND_API_KEY);
await resend.emails.send({
from: `${data.output.name} <${process.env.RESEND_FROM_EMAIL || "onboarding@resend.dev"}>`,
from: `${data.output.name} <${env.RESEND_FROM_EMAIL || "onboarding@resend.dev"}>`,
replyTo: `${data.output.name} <${data.output.email}>`,
to: [config.authorEmail],
to: [env.RESEND_TO_EMAIL],
subject: `[${config.siteName}] Contact Form Submission`,
text: data.output.message,
});

View File

@ -1,5 +1,6 @@
"use client";
import { env } from "../../lib/env";
import { useActionState, useState } from "react";
import TextareaAutosize from "react-textarea-autosize";
import Turnstile from "react-turnstile";
@ -104,7 +105,7 @@ const ContactForm = () => {
</div>
<div style={{ margin: "1em 0" }}>
<Turnstile sitekey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || "1x00000000000000000000AA"} fixedSize />
<Turnstile sitekey={env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || "1x00000000000000000000AA"} fixedSize />
</div>
{!pending && formState.errors?.["cf-turnstile-response"] && (
<span className={styles.errorMessage}>{formState.errors["cf-turnstile-response"][0]}</span>

View File

@ -7,7 +7,7 @@ import { SkipToContentLink, SkipToContentTarget } from "../components/SkipToCont
import { setRootCssVariables } from "../lib/helpers/styles";
import * as config from "../lib/config";
import { BASE_URL, MAX_WIDTH } from "../lib/config/constants";
import defaultMetadata from "../lib/config/metadata";
import defaultMetadata from "../lib/config/seo";
import type { Metadata } from "next";
import type { Person, WebSite } from "schema-dts";
@ -41,7 +41,7 @@ const RootLayout = ({ children }: Readonly<{ children: React.ReactNode }>) => {
height: `${ogImage.height}`,
},
sameAs: [
BASE_URL,
`${BASE_URL}`,
`https://${config.authorSocial?.mastodon}`,
`https://github.com/${config.authorSocial?.github}`,
`https://bsky.app/profile/${config.authorSocial?.bluesky}`,

View File

@ -1,6 +1,6 @@
import { connection } from "next/server";
import CountUp from "../../../components/CountUp";
import redis from "../../../lib/helpers/redis";
import redis from "../../../lib/redis";
import { siteLocale } from "../../../lib/config";
const HitCounter = async ({ slug }: { slug: string }) => {

View File

@ -1,3 +1,4 @@
import { env } from "../../../lib/env";
import { Suspense } from "react";
import { JsonLd } from "react-schemaorg";
import { CalendarIcon, TagIcon, SquarePenIcon, EyeIcon } from "lucide-react";
@ -20,7 +21,6 @@ import styles from "./page.module.css";
export const dynamicParams = false;
// https://nextjs.org/docs/app/building-your-application/rendering/partial-prerendering#using-partial-prerendering
// eslint-disable-next-line camelcase
export const experimental_ppr = true;
export const generateStaticParams = async () => {
@ -122,7 +122,7 @@ const Page = async ({ params }: { params: Promise<{ slug: string }> }) => {
</div>
{/* only count hits on production site */}
{process.env.NEXT_PUBLIC_VERCEL_ENV !== "development" && process.env.NODE_ENV !== "development" ? (
{env.VERCEL_ENV === "production" ? (
<div
className={styles.metaItem}
style={{

View File

@ -1,3 +1,4 @@
import { env } from "../../lib/env";
import { notFound } from "next/navigation";
import { graphql } from "@octokit/graphql";
import { GitForkIcon, StarIcon } from "lucide-react";
@ -20,7 +21,7 @@ export const metadata = addMetadata({
const getRepos = async () => {
// don't fail the entire site build if the required API key for this page is missing
if (!process.env.GITHUB_TOKEN) {
if (!env.GITHUB_TOKEN) {
console.warn(`ERROR: I can't fetch any GitHub projects without "GITHUB_TOKEN" set! Disabling projects page.`);
// just return a 404 since this page would be blank anyways
@ -64,7 +65,7 @@ const getRepos = async () => {
limit: 12,
headers: {
accept: "application/vnd.github.v3+json",
authorization: `token ${process.env.GITHUB_TOKEN}`,
authorization: `token ${env.GITHUB_TOKEN}`,
},
request: {
// override fetch() to use next's extension to cache the response

View File

@ -1,7 +1,7 @@
import path from "path";
import glob from "fast-glob";
import { getFrontMatter } from "../lib/helpers/posts";
import { BASE_URL } from "../lib/config/constants";
import { BASE_URL, RELEASE_TIMESTAMP } from "../lib/config/constants";
import type { MetadataRoute } from "next";
const sitemap = async (): Promise<MetadataRoute.Sitemap> => {
@ -9,9 +9,9 @@ const sitemap = async (): Promise<MetadataRoute.Sitemap> => {
const routes: MetadataRoute.Sitemap = [
{
// homepage
url: BASE_URL,
url: `${BASE_URL}`,
priority: 1.0,
lastModified: new Date(process.env.RELEASE_DATE || Date.now()), // timestamp frozen when a new build is deployed
lastModified: new Date(RELEASE_TIMESTAMP), // timestamp frozen when a new build is deployed
},
];