Next.js Discord

Discord Forum

What is the "best" way to call an API route from a page?

Answered
Nile Crocodile posted this in #help-forum
Open in Discord
Nile CrocodileOP
I tried doing fetch('/api/my-route/) on one of my pages, but it gives me Error: Failed to parse URL from /api/my-route. Is it better to just hardcode that full URL? I know I can call a lot of it from the page itself, the API is making calls to Supabase and Sanity.io along with a bunch of calculations and that is why I decided to break it out to an API. However, maybe I just bring all that logic into the page itself? I added a screenshot of what this API route is doing, I just want to make sure I am doing it the best way and most performant way.
Answered by joulev
maybe I just bring all that logic into the page itself
Yes. bring all that logic into the page itself.

you can always wrap them in function(s) and call those function(s) inside the page to make the page look simpler.
View full answer

4 Replies

Answer
Nile CrocodileOP
Thanks! I’m hoping to figure out a way to automate the calculation and putting it in a Supabase table but I have yet to figure that out and need to figure it out by August 😭

And then that way I can just make a call to Supabase.
Nile CrocodileOP
Fair, I am just not 100% up to speed on Supabase. Also, thanks for marking this answered, I couldn't figure out how to do it on mobile 😂
Nile CrocodileOP
Ok so I ended up doing everything in the page but then found the cron jobs that Vercel has. So I just created that API route and then created a vercel.json with the following in it. TBH, not sure if it supports query params in the path but 🤷‍♂️

{
  "crons": [
    {
      "path": "/api/cron/rankings?division=fcs",
      "schedule": "59 23 * 8-12 0"
    }
  ]
}


I think created a table that looks like

export const weeklyFinalRankings = pgTable(
  'weekly_final_rankings',
  {
    id: serial('id').primaryKey(),
    division: varchar('division', { length: 10 }).notNull(),
    week: integer('week').notNull(),
    year: integer('year').notNull(),
    rankings: jsonb('rankings').notNull(),
  },
  (table) => ({
    isUniqueVote: unique().on(table.year, table.week),
  }),
)


🤞