Accepted answer

What are you using to bundle your application? If you're using Webpack, you can use the raw-loader and directly import the txt file into your app.

Raw loader:

Then you can simply: import txt from 'file.txt';

Either way you need to pull the data from your local file system and include it in your bundle using some method.


Have a look at PapaParse

It has the ability to read and parse local CSV files, which I think is what you are looking for.

There is also jsonfile, but that may use fs under the hood.


I ran into a similar head-banging issue for loading a local csv. The first challenge is getting webpack to include the local file in the build. The best way to do that in Webpack 5 is with asset modules:


  test: /\.(csv)$/i,
  type: 'asset',

The second challenge is encapsulating the data into a variable. As Dan says, the best way is not AJAX, but using a named import.

import blob from './foo.csv';


blob is now a string. You need to extract the encoded value that represents your file contents and decode it from base64.

const encodedData = blob.split(",")[1] 
const data = atob(encodedData)


Now data can be supplied to a csv parser (eg PapaParse).


Since you mentioned in comments that you used create-react-app for your project, the best solution at the moment would be a babel plugin called Raw.Macro.

This plugin allows you to access content of your files without a need to create-react-app eject. Provides really elegant solution without any boilerplate code.

Note: There is a small drawback that you have to re-start your webpack dev server when the file changes, because the content of a file is being embedded during the build process.

    import raw from 'raw.macro';

    function foo(){
        const jsonContent = raw('../utils/stops.json');


You could use:

<input type=file></input> 

and have the user manually give the file to your app.

Related Query

More Query from same tag