John Goofy
John Goofy

Reputation: 998

next.js: equivalent to getStaticProps() for API endpoints?

In next.js, we can pass a hint to the platform to pre-render certain pages at build time by defining a getStaticProps() in their implementation.

Is there any similar mechanism for API endpoints that we implement in pages/api/?

Example: we have a page that statically renders posts from a database or external website, and we want an API endpoint to return the exact same posts in their state at the very same time, only in JSON.

Upvotes: 0

Views: 297

Answers (1)

Danila
Danila

Reputation: 18506

I believe there is no such thing for api routes.

What you can do is save your posts to some file on disk or external storage after requesting data inside getStaticProps, and then use this file as data source for api route handler, something like that:

export const getStaticProps = async () => {
  const posts = await getPosts();

  saveSnapshot(posts);

  return {
    props: { /* ... */ }
  }
}

API handler:

export default async function handler(req, res) {
  const posts = await getPostsFromStorage();

  res.status(200).json(posts)
}

One thing to note is that depending on how you serve your app, this file might not be persisted between getStaticProps and api handler.

For example, if you are using regular VPS it will be persisted, since you probably build and run your app at the same server and environment.

But if you are using some serverless thing then your api handlers might run in different environment and have no access to build files, then you might want to use external storage for it.

Upvotes: 1

Related Questions