Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate static API routes in nextjs

I have data (JSON) in a file that I want to expose through an API. I know the data at build time but I don't know how to create static API routes or even expose the files through the API routes statically.

I googled two solutions for this:

  • Create a static page that returns a JSON file (couldn't find a solution, it always returned HTML).
  • Use the pages/api/[something] to generate the API (but it seems to always be dynamic).

My last resort is to try to access the file through the function on the /pages/api/[something].js but this is dynamic and not static.

The dynamic function that comes by default in /pages/api/hello.js folder:

export default (req, res) => {  
  res.statusCode = 200;
  res.json({ name: "John Doe" });
};

What is the typical strategy here? I feel that I'm missing something.

like image 733
Artur Carvalho Avatar asked Feb 24 '26 16:02

Artur Carvalho


2 Answers

FWIW, this is the dynamic way I found to generate the API dynamically:

// on file /pages/api/[article].js
import { getArticle } from "../../lib/api";

export default (req, res) => {

  // It gets an article from a file, also can be used with getStaticProps
  const article = getPost({article: req.article}); 
  
  res.statusCode = 200;

  // returns the JSON.
  res.json(article);
}

I'd still prefer to have it static to not need any serverless functions running.

like image 164
Artur Carvalho Avatar answered Feb 26 '26 05:02

Artur Carvalho


Use the pages/api/[something] to generate the API (but it seems to always be dynamic).

No it's not dynamic. From [something].js,if you export getStaticPath(this will generate static routes for you) and getStaticProps(this will inject the data to be served from corresponding routes), next build will have your static files generated, and ready to be served as api pages with raw json data.

Hope this had been what you were trying to solve.

like image 33
Yves Ng Avatar answered Feb 26 '26 06:02

Yves Ng