Next.js Discord

Discord Forum

Vercel/Next.js Cache Help

Unanswered
Flame-colored Tanager posted this in #help-forum
Open in Discord
Flame-colored TanagerOP
I have some questions about the best way to implement the following functionality:

I have some college course data (~3800 rows) stored in a MySQL database and an api route that returns individual course data based on filters like ids, etc.

What I want is also the functionality to return all course data. Due to the nature of the data, i don't think it makes sense to requery the database on each request since it won't be changing for several months at a time.

I've been reading the documentation on vercel/next.js caching but admittedly, im a little lost and confused on what the best way to actually implement that api functionality would be.

Currently, I set the headers for Cache-Control if no query params are provided because I'm not really interested in caching other types of returns. Only when no query params are provided do I want to return the cached response of all the courses.

This what I currently have but I'm kind of just copying the documentation examples and don't really understand it:

    const { param1, param2, param3 } = req.query
    // handle each param
    // ...
    // if no params provided, i do this
    const _maxAge = 1 * 60 * 60 * 24 * 7; // 1 week
    res.setHeader(
      "Cache-Control",
      `public, s-maxage=${_maxAge}, stale-while-revalidate`,
    );
    // return res.status(200).json({ all courses })


Is this sufficient? Would it better to use the edge runtime for this or is there a better alternative? The JSON response is ~2MB so (i think) it's not crazy large but I still think there's a better alternative to requerying the database each time, I'm just not sure how to implement them.

I'm also comfortable switching to route handlers if needed, the api routes are pretty simple so shouldn't be much an issue switching over.

Thanks 🤞:AlienDance:

0 Replies