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");

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

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

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