https://www.seancdavis.com/posts/render-json-page-with-nextjs/
Say you have some JSON code — e.g. { "hello": "world" }
— that you want to return as some page in your Next.js site. Here’s what you can do:
const Sitemap = () => null;
export const getServerSideProps = async ({ res }) => {
const content = { hello: "World" };
res.setHeader("Content-Type", "application/json");
res.write(JSON.stringify(content));
res.end();
return {
props: {},
};
};
export default Sitemap;
This is essentially the same as the post I wrote on building an XML page with Next.js. Here's how this code works:
- Render
null
(or nothing) from the page component. - Use
getServerSideProps
to build a JavaScript object, convert it to a JSON string, and hijack the Next.js response to set the appropriate headers and render the content.
Note that we still want to return the props
object or Next gets mad.
Không có nhận xét nào:
Đăng nhận xét