Setting global $axios headers in NuxtJS is a common requirement, especially when handling information such as authentication tokens that need to be consistently passed across multiple requests. Below are the steps to configure axios headers globally in your NuxtJS project:
Step 1: Install the @nuxtjs/axios module
First, ensure that the @nuxtjs/axios module is installed in your NuxtJS project. If not, install it using the following command:
bashnpm install @nuxtjs/axios
Or:
bashyarn add @nuxtjs/axios
Step 2: Configure axios in nuxt.config.js
In the nuxt.config.js file, register the axios module and set basic configurations:
javascriptexport default { modules: [ '@nuxtjs/axios', ], axios: { // API base URL baseURL: 'https://api.example.com', }, }
Step 3: Set global request headers
Use the plugin system to set global request headers. Create a plugin file, such as plugins/axios.js, and define the headers:
javascriptexport default function({ $axios }) { // Set request headers $axios.onRequest(config => { config.headers.common['Authorization'] = `Bearer token_string_here`; config.headers.common['Content-Type'] = 'application/json'; return config; }); }
Step 4: Register the plugin in nuxt.config.js
Finally, register the plugin in nuxt.config.js:
javascriptexport default { plugins: [ '~/plugins/axios' ], }
Example Scenario
Suppose you're developing an application requiring user authentication where every API request must include a JWT (JSON Web Token). After user login, store the JWT and automatically add it to request headers via the plugin on each request. This ensures all requests are authenticated.
Conclusion
By following these steps, you can configure global $axios headers in your NuxtJS application. This approach is valuable for managing authentication tokens, content types, and other reusable request parameters across multiple requests. It enhances code maintainability and reusability, ensuring all API requests adhere to expected formats and authentication requirements.