Skip to content

Instantly share code, notes, and snippets.

@jsjoeio
Created July 20, 2021 15:24
Show Gist options
  • Save jsjoeio/58d99cac4ee4d73cbc8391c7b2ed1808 to your computer and use it in GitHub Desktop.
Save jsjoeio/58d99cac4ee4d73cbc8391c7b2ed1808 to your computer and use it in GitHub Desktop.
Vercel serverless function protected by secret to be used in cron job
import { NextApiRequest, NextApiResponse } from "next"
// ----------------------------------------------------------------------------
// To test this from the command line, run:
// curl --request POST \
// --url 'http://localhost:3000/api/<endpoint>' \
// --header 'Authorization: Bearer API_SECRET_KEY' \
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === "POST") {
try {
const { authorization } = req.headers
if (authorization === `Bearer ${process.env.API_SECRET_KEY}`) {
res.status(200).json({ success: true })
} else {
res.status(401).json({ success: false })
}
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
} else {
res.setHeader("Allow", "POST")
res.status(405).end("Method Not Allowed")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment