In this episode, we dive into two clean and common ways to set up the base URL in Axios, which is a super handy library for making HTTP requests in JavaScript and frontend frameworks like Vue. You’ll see a basic app in action, grabbing some example data from JSONPlaceholder, and we use that as a starting point to refactor our Axios setup for cleaner, more maintainable code.
First up, we look at the old way—having a config file with your API URL that you import wherever you call Axios. It works, but it can get repetitive and a bit messy.
Next, we walk through setting the Axios base URL globally in main.js
by tweaking Axios’s defaults. That way, you don’t have to keep pasting the full URL everywhere—just make requests using paths like /posts
. This is nice and simple, but if you add a lot of custom Axios settings at once, your main entry file can get cluttered.
So, we move on to the preferred approach for bigger and/or tidier apps: making a custom Axios instance. By creating an axios/index.js
, you set all your defaults—like the base URL and any headers—in one place, and then import your version of Axios everywhere in your app. This is especially good if your base URL might change depending on the environment (development, production, etc.), since you can easily feed in config or environment variables.
By the end, you’ll know two solid methods for keeping your Axios setup tidy and maintainable, with tips on which one might work best for your project!