Keeping keys secret on Vercel
Anything in a public repo, or in JavaScript sent to the browser, is visible to everyone. The fix is a small serverless function. The browser calls your function, and your function calls the museum with the key.
- Add
.env* to .gitignore before your first commit.
- Store the key in Vercel, either from the project's Settings → Environment Variables page or with
vercel env add HARVARD_API_KEY.
- For local development, run
vercel env pull to download it to a git-ignored .env.local file.
- Create a function such as
api/harvard.js that reads process.env.HARVARD_API_KEY, and have your page fetch /api/harvard?q=….
// api/harvard.js — runs on Vercel's servers, never in the browser
export default async function handler(req, res) {
const q = encodeURIComponent(req.query.q ?? "");
const url = `https://api.harvardartmuseums.org/object` +
`?apikey=${process.env.HARVARD_API_KEY}&keyword=${q}&hasimage=1&size=12`;
const museum = await fetch(url);
// Cache for a day at Vercel's edge: faster pages, fewer API calls
res.setHeader("Cache-Control", "s-maxage=86400, stale-while-revalidate");
res.status(museum.status).json(await museum.json());
}
If a key gets committed by mistake
Deleting the file is not enough, because the key stays in the git history. Ask the provider for a new key, stop using the old one, and update the Vercel environment variable.