I am building a small personal project and I have a data.json file stored in the same folder as my script. I tried using the fetch API, but I keep running into CORS policy errors because I am opening the HTML file directly from my file system rather than through a local server. Is there a way to import this JSON data directly into my JavaScript variable using the import statement or perhaps a file reader, and what are the security implications of accessing local files this way?
3 answers
To handle local JSON files without a server, the most modern approach is using ES6 modules. You can add type="module" to your script tag and then use the import statement with a dynamic import assertion. For example: import data from './data.json' assert { type: 'json' };. However, keep in mind that many browsers still enforce strict security even for local files. If the import doesn't work, the best workaround for development is to use a simple VS Code extension like Live Server. This treats your folder as a local host, allowing the standard Fetch API to work seamlessly without those annoying CORS blocks while keeping your code clean and production-ready.
If this is just for a local tool and you don't want to deal with a server at all, have you tried changing your .json file to a .js file and just assigning the object to a global constant?
You can use the Fetch API, but you must run a local environment. Without a server, browsers block requests to the local file system for security.
xactly, Karen. It is important to note for anyone reading this that "File://" protocol is very limited. Setting up a Node.js local environment is the standard industry practice now.
Thomas, while that definitely bypasses the security errors, it feels a bit like a "hack" because it changes the data format. A more robust way if the user is actually interacting with the file system is the FileReader API. You can have an element, and once the user selects the JSON file, JavaScript can read the contents as a string and parse it using JSON.parse(). It keeps the data as a true JSON file while satisfying the browser's security requirements for user-initiated file access.