---
id: code-splitting
title: 'API Slices: Code Splitting and Generation'
sidebar_label: Code Splitting
hide_title: true
---

&nbsp;

# API Slices: Code Splitting and Generation

Each API slice allows [additional endpoint definitions to be injected at runtime](../../usage/code-splitting.mdx) after the initial API slice has been defined. This can be beneficial for apps that may have _many_ endpoints.

The individual API slice endpoint definitions can also be split across multiple files. This is primarily useful for working with API slices that were [code-generated from an API schema file](../../usage/code-generation.mdx), allowing you to add additional custom behavior and configuration to a set of automatically-generated endpoint definitions.

Each API slice object has `injectEndpoints` and `enhanceEndpoints` functions to support these use cases.

## `injectEndpoints`

#### Signature

```ts no-transpile
const injectEndpoints = (endpointOptions: InjectedEndpointOptions) =>
  EnhancedApiSlice

interface InjectedEndpointOptions {
  endpoints: (build: EndpointBuilder) => NewEndpointDefinitions
  /**
   * Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.
   *
   * If set to `true`, will override existing endpoints with the new definition.
   * If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.
   * If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.
   */
  overrideExisting?: boolean | 'throw'
}
```

#### Description

Accepts an options object containing the same `endpoints` builder callback you would pass to [`createApi.endpoints`](../createApi.mdx#endpoints). Any endpoint definitions defined using that builder will be merged into the existing endpoint definitions for this API slice using a shallow merge, so any new endpoint definitions will override existing endpoints with the same name.

Returns an updated and enhanced version of the API slice object, containing the combined endpoint definitions.

Endpoints will not be overridden unless `overrideExisting` is set to `true`. If not, a development mode warning will be shown to notify you if there is a name clash between endpoint definitions.

This method is primarily useful for code splitting and hot reloading.

## `enhanceEndpoints`

#### Signature

```ts no-transpile
const enhanceEndpoints = (endpointOptions: EnhanceEndpointsOptions) =>
  EnhancedApiSlice

interface EnhanceEndpointsOptions {
  addTagTypes?: readonly string[]
  endpoints?: Record<string, Partial<EndpointDefinition>>
}
```

#### Description

Any provided tag types or endpoint definitions will be merged into the existing endpoint definitions for this API slice. Unlike `injectEndpoints`, the partial endpoint definitions will not _replace_ existing definitions, but are rather merged together on a per-definition basis (ie, `Object.assign(existingEndpoint, newPartialEndpoint)`).

Returns an updated and enhanced version of the API slice object, containing the combined endpoint definitions.

This is primarily useful for taking an API slice object that was code-generated from an API schema file like OpenAPI, and adding additional specific hand-written configuration for cache invalidation management on top of the generated endpoint definitions.

For example, `enhanceEndpoints` can be used to modify caching behavior by changing the values of `providesTags`, `invalidatesTags`, and `keepUnusedDataFor`:

```ts
// file: api.ts noEmit
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const api = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  endpoints: (build) => ({
    getUserByUserId: build.query({
      query() {
        return ''
      },
    }),
    patchUserByUserId: build.mutation({
      query() {
        return ''
      },
    }),
    getUsers: build.query({
      query() {
        return ''
      },
    }),
  }),
})

// file: enhanceEndpoints.ts
import { api } from './api'

const enhancedApi = api.enhanceEndpoints({
  addTagTypes: ['User'],
  endpoints: {
    getUserByUserId: {
      providesTags: ['User'],
    },
    patchUserByUserId: {
      invalidatesTags: ['User'],
    },
    // alternatively, define a function which is called with the endpoint definition as an argument
    getUsers(endpoint) {
      endpoint.providesTags = ['User']
      endpoint.keepUnusedDataFor = 120
    },
  },
})
```