Nuxt.js is a framework built on Vue.js for developing server-rendered applications (SSR), static sites (SSG), or single-page applications (SPA). In Nuxt.js, you can configure baseURL by setting environment variables, which serves as the base path for API requests.
In a Nuxt.js project, you can configure baseURL in two locations:
- nuxt.config.js: This is the location for setting project-level configuration. You can define a default
baseURLhere, which applies to both development and production environments, but it can be overridden by environment variables. - Environment Variables: Use
.envfiles or environment variables directly to setbaseURL, enabling different values for various environments (development, production, etc.).
Setting baseURL in nuxt.config.js
You can define baseURL by setting the baseURL option in the axios module within the nuxt.config.js file. This module automatically injects baseURL into the axios instance used throughout the application.
javascriptexport default { // ... axios: { // Base URL for API server baseURL: process.env.BASE_URL || 'http://localhost:3000' }, // ... }
In the above example, process.env.BASE_URL is an environment variable that you can set in your project's .env file or directly in the command line. If BASE_URL is not set, it defaults to 'http://localhost:3000' as the fallback value.
Setting baseURL via .env File
Create a .env file in the root directory of your project and set the BASE_URL environment variable:
shellBASE_URL=https://api.example.com
Next, install the @nuxtjs/dotenv module to enable Nuxt.js to read the .env file:
bashnpm install @nuxtjs/dotenv
Then, include this module in your nuxt.config.js file:
javascriptrequire('dotenv').config(); export default { modules: [ '@nuxtjs/dotenv', ], // ... axios: { baseURL: process.env.BASE_URL }, // ... }
Setting Environment Variables at Runtime
In development mode, you can set environment variables when starting the Nuxt.js server:
bashBASE_URL=https://api.example.com nuxt
In production mode, if using a process manager like PM2, set environment variables when starting the application:
bashBASE_URL=https://api.example.com pm2 start npm --name "my-app" -- run start
Alternatively, set environment variables in your production deployment script.
Ensure you follow security and best practices guidelines for the platform or service you're using. For example, on platforms like Vercel, Netlify, or Heroku, you can safely set environment variables through their control panels.
After setting these variables, all HTTP requests in your Nuxt.js application will automatically use the correct baseURL, whether in development or production environments.