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:
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With