Home

Render JSON Page with Next.js

Build a JSON page component with Next.js.

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.

A playground with this example is shown below (source):

Let's Connect

Keep Reading

Render XML Page with Next.js

Learn how to generate an XML page with Next.js.

Jul 23, 2022

Run React Effect Hook only Once in Strict Mode

Running React in strict mode with Next.js can lead to useEffect callbacks with zero dependencies to run twice in development. Here’s a way around that.

Jun 25, 2022

Resetting State on Next.js Route Change

Component state doesn't change when navigating between dynamic routes in Next.js that use the same component. useEffect can help.

May 21, 2022