To fetch and read a local JSON file (such as ./data/config.json) in a browser or modern runtime, use fetch(url) with async / await, verify response.ok so HTTP errors like 404 are caught explicitly, and parse the body with await response.json() inside a try / catch block. Because browsers block fetch() over file:// URLs due to origin/CORS rules, serve the project from a local HTTP server (such as Vite, Live Server, or npx serve) rather than opening HTML directly from disk.
1. Fetching and Parsing a Local JSON File with fetch() and async / await
Validate the file path, call fetch() with a relative or root-relative URL, check response.ok, and parse the JSON payload safely without mutating the returned structure:
// Fetch and parse a local JSON file over HTTP with status and input guards
async function loadLocalJson(filePath, { timeoutMs = 8000 } = {}) {
if (typeof filePath !== "string" || filePath.trim() === "") {
throw new TypeError("Expected a non-empty JSON file path.");
}
const controller = new AbortController();
const timerId = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(filePath, {
method: "GET",
headers: { Accept: "application/json" },
signal: controller.signal
});
if (!response.ok) {
throw new Error(`Failed to load "${filePath}" (HTTP ${response.status} ${response.statusText})`);
}
const data = await response.json();
return data;
} finally {
clearTimeout(timerId);
}
}
// Example usage:
// loadLocalJson("./data/settings.json")
// .then((settings) => console.log("Loaded JSON:", settings))
// .catch((err) => console.error(err));
- Explicit HTTP status guard:
fetch()does not reject on HTTP404or500by default, so checking!response.okprevents treating error pages as valid data. - Timeout protection via
AbortController: Aborts hung requests cleanly and always clears the timer infinally.
2. Reading Local JSON in Node.js (When Not Serving Over HTTP)
In Node.js, a local JSON file on disk is read via fs/promises (readFile) + JSON.parse() (or static/dynamic ESM import with { with: { type: "json" } } in modern Node), because browser fetch() targets URLs rather than arbitrary OS filesystem paths:
// Read and parse a local JSON file safely in Node.js using fs/promises
import { readFile } from "node:fs/promises";
import path from "node:path";
async function readJsonFileInNode(relativeOrAbsolutePath, baseDir = process.cwd()) {
if (typeof relativeOrAbsolutePath !== "string" || relativeOrAbsolutePath.trim() === "") {
throw new TypeError("Expected a valid file path.");
}
const resolvedPath = path.resolve(baseDir, relativeOrAbsolutePath);
const rawText = await readFile(resolvedPath, "utf8");
const parsed = JSON.parse(rawText);
return Object.freeze(parsed);
}
// Example usage:
// const config = await readJsonFileInNode("./config.json");
- UTF-8 text +
JSON.parse(): Explicitly specifying"utf8"returns a string thatJSON.parse()decodes into a JS value. - Path resolution guard:
path.resolve(baseDir, ...)normalizes relative paths cleanly across platforms.
3. Common Traps to Avoid
Fetching and reading local JSON files often runs into a few pitfalls:
- Opening an HTML file via
file://in the browser: Browsers rejectfetch()onfile://origins with network/CORS errors—always run a local dev or static HTTP server. - Forgetting
awaitonresponse.json():response.json()returns aPromise, not the parsed object—forgettingawaityields a pending Promise instead of your JSON data. - Assuming
fetch()rejects on404 Not Found: A missing JSON file still resolvesfetch()withresponse.ok === falseand an HTML404body, which causesresponse.json()to throw a syntax error unlessresponse.okis checked first.
TL;DR: In the browser over a local HTTP server, call await fetch("./file.json"), check response.ok, and parse with await response.json() inside try / catch (or use fs/promises + JSON.parse() in Node.js).
