Set a shared base URL
An API service has a common origin or path prefix for its endpoints.
Redux Toolkit · Function
fetchBaseQuery is a lightweight wrapper around fetch that creates an RTK Query-compatible baseQuery function. Configure shared request behavior once, then use the returned function in createApi.
fetchBaseQuery creates an RTK Query-compatible request function around the browser fetch API. Configure it with a base URL and optional request behavior, then assign the resulting function to createApi's baseQuery field so endpoints can supply relative paths or request descriptions.
fetchBaseQuery(options)| Name | Type | Description |
|---|---|---|
options | FetchBaseQueryArgs | Configuration object containing standard fetch RequestInit settings plus baseUrl, prepareHeaders, optional fetch, paramsSerializer, and timeout. |
A data-fetching function compatible with RTK Query's baseQuery configuration option.
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const api = createApi({
reducerPath: 'postsApi',
baseQuery: fetchBaseQuery({ baseUrl: 'https://api.example.com/' }),
endpoints: (build) => ({
getPosts: build.query<Post[], void>({
query: () => 'posts',
}),
}),
})
type Post = { id: number; title: string }Creates an RTK Query API whose endpoint requests are resolved relative to the configured base URL.
An API service has a common origin or path prefix for its endpoints.
Authentication or tracing headers must be applied to every outgoing request.
The application needs custom query-string encoding or a request deadline.
fetchBaseQuery is a factory that returns a baseQuery function compatible with RTK Query. It wraps fetch and is configured by passing its result to createApi's baseQuery option.
Follow-up: What should you use when its behavior is insufficient? Wrap it to add application-specific behavior, or implement a custom baseQuery function.
The baseUrl establishes the common URL prefix for endpoint requests. An endpoint can then return a relative path, which fetchBaseQuery combines with that prefix.
Follow-up: How can request headers be customized consistently? Supply prepareHeaders, which can inject headers on every request.
It accepts standard fetch RequestInit options along with RTK Query-specific options such as baseUrl, prepareHeaders, paramsSerializer, an override fetch function, and timeout. This keeps ordinary fetch configuration available while adding API-service conveniences.
Follow-up: How would query parameters be serialized differently from the default? Provide a paramsSerializer function in the configuration.
createApibaseQueryprepareHeadersparamsSerializerRequestInit