How to Load Loacl Json Data from a File in Next.js

Musheerk
2 min readAug 4, 2023

--

Sure! Here’s a step-by-step guide with explanations on how to load data from a file in Next.js:

  1. Prerequisites: Before starting, ensure that you have a basic Next.js project set up and deployed on Vercel. Also, you should be familiar with Next.js API routes and have SWR (React hooks for data fetching) installed in your project.
  2. Set up the JSON data: Create a folder named “json” at the root of your project. Inside this folder, create a file named “data.json” and add some sample JSON data to it. For example:
{
"record": {
"id": 8221,
"uid": "a15c1f1d-9e4e-4dc7-9c45-c04412fc5064",
"name": "Next.js",
"language": "JavaScript"
}
}
  1. Create the API route: Inside the “pages/api” folder, create a file named “staticdata.js”. This file will be a serverless function that reads the “data.json” file and returns its content as a response.
import path from 'path';
import { promises as fs } from 'fs';

export default async function handler(req, res) {
// Find the absolute path of the "json" directory
const jsonDirectory = path.join(process.cwd(), 'json');
// Read the "data.json" file
const fileContents = await fs.readFile(jsonDirectory + '/data.json', 'utf8');
// Return the content of the data file in JSON format
res.status(200).json(JSON.parse(fileContents));
}
  1. Display the data using SWR: Inside the “pages/index.js” file, replace its content with the following code:
import useSWR from 'swr';

// Write a fetcher function to wrap the native fetch function and return the result of a call to the URL in JSON format
const fetcher = (url) => fetch(url).then((res) => res.json());

export default function Index() {
// Set up SWR to run the fetcher function when calling "/api/staticdata"
// There are 3 possible states: (1) "loading" when data is null (2) "ready" when the data is returned (3) "error" when there was an error fetching the data
const { data, error } = useSWR('/api/staticdata', fetcher);

// Handle the error state
if (error) return <div>Failed to load</div>;
// Handle the loading state
if (!data) return <div>Loading...</div>;
// Handle the ready state and display the result contained in the data object mapped to the structure of the JSON file
return (
<div>
<h1>My Framework from file</h1>
<ul>
<li>Name: {data.record.name}</li>
<li>Language: {data.record.language}</li>
</ul>
</div>
);
}
  1. Final Steps:
  • Make sure you have installed SWR in your project using yarn add swr or npm install swr.
  • Run your application locally using npm run dev. Browse to localhost:3000 to see the result.
  • Deploy your application to Vercel or your preferred hosting service.

Now you should see the JSON data loaded from the file and displayed on your Next.js page. This approach ensures that your JSON data is stored privately in your application and is fetched securely using an API endpoint.

--

--