Skip to content

Instantly share code, notes, and snippets.

@jakejarvis
Last active July 31, 2021 01:06
Show Gist options
  • Save jakejarvis/fb70c27c752836bff277d16f28163e00 to your computer and use it in GitHub Desktop.
Save jakejarvis/fb70c27c752836bff277d16f28163e00 to your computer and use it in GitHub Desktop.
My Vercel function boilerplate
import { VercelRequest, VercelResponse } from "@vercel/node";
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export default (req: VercelRequest, res: VercelResponse) => {
try {
// some rudimentary error handling
if (req.method !== "GET") {
throw new Error(`Method ${req.method} not allowed.`);
}
// let Vercel edge and browser cache results for 5 mins
res.setHeader("Cache-Control", "public, max-age=300, s-maxage=300, stale-while-revalidate");
// permissive access control headers
res.setHeader("Access-Control-Allow-Methods", "GET");
res.setHeader("Access-Control-Allow-Origin", "*");
// return in JSON format
res.status(200).json({ status: "OK" });
} catch (error) {
console.error(error);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
res.status(400).json({ message: error.message });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment