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

Generate Dynamic JSON Pages with Next.js

Two methods for generating JSON pages with Next.js. One that updates on every request, the other on every build.

Jun 10, 2021

Open External next/link Links in a New Tab

Add a component that dynamically swaps between next/link and a native anchor tag, and decides how to write the target attribute, all based on the href property.

Jun 30, 2022