Static json
files can be used to store data that does not change regularly, and is used by multiple pages. These files can be stored in your applications public folder, and loaded directly with a GET
request. This approach can have security concerns however. A possible solution is to:
- Store your
json
files in a private folder inside your application - Construct an API endpoint to load these files using the file system
- Connect to the API endpoint in your front-end and display the data
Prerequisites
Before getting started, you should be able to:
- Deploy a
Next.js
app on Vercel - Familiar with
Next.js
API routes - Install
SWR
in your project
Set up the json
data
Given a basic Next.js
project created with npx create-next-app@latest
or a new template on Vercel, let's create a folder called json
at the root of the project, and inside it, create a file called data.json
.
Begin by pasting the following content into the data.json
file:
1{2 "record": {3 "id": 8221,4 "uid": "a15c1f1d-9e4e-4dc7-9c45-c04412fc5064",5 "name": "Next.js",6 "language": "JavaScript"7 }8}
Add the API route
Next add a file called staticdata.js
inside the pages/api
folder. This will create a Serverless Function that will load the json data from the file, and return it as a response.
Now paste the following code in the staticdata.js
file:
1import path from 'path';2import { promises as fs } from 'fs';3
4export default async function handler(req, res) {5 //Find the absolute path of the json directory6 const jsonDirectory = path.join(process.cwd(), 'json');7 //Read the json data file data.json8 const fileContents = await fs.readFile(jsonDirectory + '/data.json', 'utf8');9 //Return the content of the data file in json format10 res.status(200).json(fileContents);11}
Display the data using SWR
Inside the index.js
file, located in the pages
folder, replace the content with the following code:
1//useSWR allows the use of SWR inside function components2import useSWR from 'swr';3
4//Write a fetcher function to wrap the native fetch function and return the result of a call to url in json format5const fetcher = (url) => fetch(url).then((res) => res.json());6
7export default function Index() {8 //Set up SWR to run the fetcher function when calling "/api/staticdata"9 //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 data10 const { data, error } = useSWR('/api/staticdata', fetcher);11
12 //Handle the error state13 if (error) return <div>Failed to load</div>;14 //Handle the loading state15 if (!data) return <div>Loading...</div>;16 //Handle the ready state and display the result contained in the data object mapped to the structure of the json file17 return (18 <div>19 <h1>My Framework from file</h1>20 <ul>21 <li>Name: {data.record.name}</li>22 <li>Language: {data.record.language}</li>23 </ul>24 </div>25 );26}
- Make sure you installed
swr
in your project usingyarn add swr
ornpm install swr
- Run your application locally using
npm run dev
When you browse to localhost:3000
, you should see the same content as on this page. You can now deploy your application to Vercel to produce the same results.
That's it!
As reference:
- Repository for the source code used above
- Get started with
SWR
to take advantage of keeping your data fresh without having to write additional code - Learn more about API routes in
Next.js