This guide will show how to read a JSON file inside a Next.js application and display its data.
First, we need to import the file system library from Node.js, which we'll use to read our file.
import { promises as fs } from 'fs';
In Next.js, create a new Server Component, which is the default in the App Router.
This component is rendered entirely on the server, which allows for securely fetching data such as JSON files or talking directly to your database.
import { promises as fs } from 'fs';
export default async function Page() { //...}
Next, we'll read the file. In this case, we're reading a JSON file. We use the readFile
function from the fs
library. We also use the process.cwd
function to get the current working directory, and append the relative path to our file.
import { promises as fs } from 'fs';
export default async function Page() { const file = await fs.readFile(process.cwd() + '/app/data.json', 'utf8'); //...}
The 'utf8'
argument tells Node to interpret the file as a UTF-8 encoded text file. The example JSON file we're reading at app/data.json
looks as follows:
{ "title": "My Title", "content": "Lorem Ipsum"}
Now, we'll parse the file's contents. The readFile
function returns the contents as a string, so we use JSON.parse
to turn it into an object. Finally, we use the data in our Server Component.
import { promises as fs } from 'fs';
export default async function Page() { const file = await fs.readFile(process.cwd() + '/app/data.json', 'utf8'); const data = JSON.parse(file);
return ( <div> <h1>{data.title}</h1> <p>{data.content}</p> </div> );}
Now, whenever you visit this page, Next.js will load the data from the file, and display it on the page.
The Next.js App Router supports colocation of your project files. This means you can safely organize your project files inside route segments in the App Router without accidentally making them routable. Even though route structure is defined through folders, a route is not publicly accessible until a page.js
or route.js
file is added to a route segment.