Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set global API baseUrl used in useFetch in Nuxt 3

How do I set the baseUrl that is used in the useFetch composable globally (maybe nuxt.config.ts)?

How can I avoid defining it in every useFetch?

like image 283
Dickson Afful Avatar asked Sep 05 '25 13:09

Dickson Afful


2 Answers

You can define the baseURL in your nuxt.config.js|ts like this:

import { defineNuxtConfig } from 'nuxt'

export default defineNuxtConfig({
  // ...
  runtimeConfig: {
    public: {
      baseURL: process.env.BASE_URL || 'https://api.example.com/',
    },
  },
  // ...

(or use a fixed value or only the environment variable - as you like)

And add this composable:

// /composables/useMyFetch.js

export const useMyFetch = (request, opts) => {
  const config = useRuntimeConfig()

  return useFetch(request, { baseURL: config.public.baseURL, ...opts })
}

If you want type safety, you can achieve it like this:

// /composables/useMyFetch.ts

export const useMyFetch: typeof useFetch = (request, opts?) => {
  const config = useRuntimeConfig()

  return useFetch(request, { baseURL: config.public.baseURL, ...opts })
}

You can then use useMyFetch as replacement for useFetch - but with baseURL being set :-)

like image 55
some-user Avatar answered Sep 08 '25 11:09

some-user


The following composable could be set
/composables/useJsonP.ts

export const useJsonP = async (path) => {
  return await useFetch(() => `https://jsonplaceholder.typicode.com/${path}`)
}

And you could call this in your view

<script setup>
const jsonP = await useJsonP('todos/1')
</script>

<template>
  <div>
    <pre>{{ jsonP.data }}</pre>
  </div>
</template>

That way, no need to define it somewhere and hack somehow the configuration. You do have a simple way of defining reusable pieces of code, that are directly imported into your components/views thanks to the DX of Nuxt.

like image 23
kissu Avatar answered Sep 08 '25 11:09

kissu