Next.js Discord

Discord Forum

CRON_SECRET typescript error

Unanswered
Prairie yellowjacket posted this in #help-forum
Open in Discord
Prairie yellowjacketOP
Hi, im attempting to implement vercel cron into my nextjs project. To secure my API route (pages directory), I am following this snippet: https://vercel.com/docs/cron-jobs/manage-cron-jobs#securing-cron-jobs

however using this code I get a typescript error:

Cannot invoke an object which is possibly 'undefined'.ts(2722)
'req.headers.get' is possibly 'undefined'.ts(18048)
This expression is not callable.
  No constituent of type 'string | string[]' is callable.ts(2349)
string | string[] | undefined


Here is the relevent code:

import { addMeetingInAnHourEvent } from "@/slices/event/services";
import type { NextApiRequest, NextApiResponse } from "next";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // ignore possibly undefined error as header is guaranteed according to docs: https://vercel.com/docs/cron-jobs/manage-cron-jobs#securing-cron-jobs

  const authHeader = req.headers.get("authorization");
  if (
    !process.env.CRON_SECRET ||
    authHeader !== `Bearer ${process.env.CRON_SECRET}`
  ) {
    return res.status(401).json({ message: "Unauthorized", success: false });
  }

  if (req.method !== "GET") {
    return res.status(403).json({ message: "method must be GET" });
  }

  return res.status(200).json({ message: "success" });
}

I just want to confirm: can I assume the the cron secret will always be included as a header?

17 Replies

Sora
so its should be req.headers.authorization right?
Prairie yellowjacketOP
i just ts ignored it lmao
its been working fine
@Sora so its should be req.headers.authorization right?
Yes. req.headers.get("foo") is the app router syntax, req.headers.foo is the pages router syntax
@joulev Yes. req.headers.get("foo") is the app router syntax, req.headers.foo is the pages router syntax
Sora
Well, do you know the reason why the code throws error 504
no, too little info to make a guess
Sora
throws an error even when empty
alrgiht thats sucks
"2 cron jobs total, each triggered once per day"
@joulev sorry for ping do u have any alternative for this?
i have nothing to add, sorry