The Complete Production SOP: How to Deploy and Run Redux Toolkit (RTK) & RTK Query API Caching in Autonomous AI Agents
Step-by-step SOP to install and run Redux Toolkit (RTK) & RTK Query API Caching in Codex, Claude Code, and Cursor. Includes verified prompts and troubleshooting.
Technical Overview & Architectural Context
Autonomous coding agents like Codex, Claude Code, Cursor, and Windsurf frequently hallucinate outdated Redux patterns when generating state management code. Left unconstrained, models default to obsolete boilerplate such as manual action creators, legacy switch-case reducers, detached Axios interceptor layers, or improper manual cache mutations instead of leveraging Redux Toolkit (RTK) and RTK Query's unified architecture. Furthermore, LLMs frequently omit critical RTK Query middleware attachment, leading to unhandled promise rejections, broken auto-caching, and silent subscription listener failures. When writing cache invalidation logic, agents often pass invalid string shapes into providesTags or invalidatesTags, or inadvertently mutate state in non-Immer contexts, generating subtle runtime reactivity bugs. This deterministic SKILL.md specification establishes strict procedural boundaries: mandating standard createSlice Immer idioms, single-point createApi endpoints with fetchBaseQuery, correct middleware chaining (getDefault().concat(api.middleware)), and typed tag invalidation matrices. By constraining agent outputs to exact TypeScript types and verified architectural recipes, the skill guarantees production-grade state management without human debugging overhead.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into agent runtime paths.
Autonomous agent engines parse contextual skills from standard hierarchical paths (.claude/skills, .cursor/rules, or ~/.agents/skills). We mount the skill directly into workspace agent configuration so tools like Claude Code and Cursor dynamically parse trigger patterns whenever Redux or RTK Query is mentioned.
mkdir -p .cursor/rules ~/.agents/skills/redux-toolkit-rtk-query-slices && curl -fsSL https://askills.dev/api/skills/redux-toolkit-rtk-query-slices/raw -o .cursor/rules/redux-toolkit-rtk-query-slices.mdc---
description: "Standardize enterprise state management with Redux Toolkit slices and RTK Query auto-caching."
globs: ["src/store/**/*.ts", "src/services/**/*.ts", "src/features/**/*.ts"]
---
# Redux Toolkit & RTK Query SOP
- Always use `createSlice` for local slice state and `createApi` with `fetchBaseQuery` for remote entities.
- Apply tag-based cache management: provide `providesTags` on queries, `invalidatesTags` on mutations.
- Add `api.middleware` to store setup: `middleware: (gDM) => gDM().concat(api.middleware)`.Use scoped globs in the skill frontmatter so the agent only loads RTK rules when inspecting store, service, or feature directories, preserving context tokens.
Ensure write permissions are workspace-scoped. If shell execution is sandboxed, avoid commands attempting to globally modify system-level Node packages.
Environment Secrets & Dependency Validation
Verify package installation and configure base URL environment variables without leaking credentials.
RTK Query services typically consume environment variables for backend API endpoints (e.g., NEXT_PUBLIC_API_URL or VITE_API_URL). Ensure required packages are tracked in package.json and verify .env.local handles secret management securely.
pnpm add @reduxjs/toolkit react-redux && echo 'NEXT_PUBLIC_API_URL="http://localhost:3000/api"' >> .env.localimport { fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const dynamicBaseQuery = fetchBaseQuery({
baseUrl: process.env.NEXT_PUBLIC_API_URL || '/api',
prepareHeaders: (headers) => {
const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
if (token) {
headers.set('authorization', `Bearer ${token}`);
}
return headers;
},
});Instruct the agent to read config parameters exclusively from process.env variables rather than hardcoding endpoints directly into fetchBaseQuery definitions.
Never prompt the agent to commit .env files containing live bearer tokens or database connection strings to source control.
Intent Matching & Trigger Invocation
Invoke deterministic code generation using exact frontmatter triggers for slices and RTK Query APIs.
When invoking Codex or Claude Code, reference the defined triggers ('create rtk query api', 'configure redux toolkit store', 'invalidate tags rtk query') to guarantee the agent executes the precise SOP pipeline.
claude "create rtk query api for managing project resources with automated tag invalidation and export hooks"import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export interface Project {
id: string;
name: string;
status: 'active' | 'archived';
}
export const projectsApi = createApi({
reducerPath: 'projectsApi',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
tagTypes: ['Project'],
endpoints: (builder) => ({
getProjects: builder.query<Project[], void>({
query: () => '/projects',
providesTags: (result) =>
result
? [...result.map(({ id }) => ({ type: 'Project' as const, id })), { type: 'Project', id: 'LIST' }]
: [{ type: 'Project', id: 'LIST' }],
}),
addProject: builder.mutation<Project, Partial<Project>>({
query: (body) => ({ url: '/projects', method: 'POST', body }),
invalidatesTags: [{ type: 'Project', id: 'LIST' }],
}),
}),
});
export const { useGetProjectsQuery, useAddProjectMutation } = projectsApi;Specify tag shapes as objects ({ type: 'Tag', id: 'ID' }) rather than flat strings to ensure granular cache invalidation without refetching entire resource arrays.
Do not skip providing the 'LIST' id tag in providesTags; otherwise, mutations that append records will fail to trigger automatic query re-fetches.
Verification, Linting & Output Quality Gate
Execute automated self-healing typechecks and store integrity tests before accepting deliverables.
Run TypeScript compiler checks and unit tests validating that the Redux store dispatches actions, captures middleware hooks, and satisfies strict types for RootState and AppDispatch.
pnpm tsc --noEmit && pnpm test -- --runInBandimport { configureStore } from '@reduxjs/toolkit';
import { setupListeners } from '@reduxjs/toolkit/query';
import { projectsApi } from './services/projectsApi';
export const store = configureStore({
reducer: {
[projectsApi.reducerPath]: projectsApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(projectsApi.middleware),
});
setupListeners(store.dispatch);
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;Always verify that setupListeners(store.dispatch) is added so refetchOnFocus and refetchOnReconnect work seamlessly in client interfaces.
Forgetting to concatenate api.middleware into getDefaultMiddleware() will allow actions to dispatch but silently crash cache lifecycle management.
Real-World Scenario: Scaffold Enterprise User Session & Permission Caching Layer with RTK Query
“create rtk query api for enterprise user sessions. Configure redux toolkit store with typed hooks (useAppDispatch, useAppSelector), tag invalidation for user profile updates, and setupListeners.”
Runtime Troubleshooting & Failure Modes
Root Cause: The configureStore invocation configured api.reducer but omitted api.middleware inside the middleware array callback.
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware)Root Cause: Endpoints define tags or tag invalidations that were not declared in the top-level tagTypes array passed to createApi.
export const api = createApi({ tagTypes: ['User', 'Project'], ... });Frequently Asked Questions (Redux Toolkit (RTK) & RTK Query API Caching SOP)
Q:Can I use Redux Toolkit (RTK) & RTK Query API Caching across Codex, Claude Code, and Cursor simultaneously?
Yes. The SKILL.md specification is runtime-agnostic. It can be symlinked into ~/.claude/skills, .cursor/rules, or root agent configs for Windsurf and Codex without syntax translation.
Q:How does Redux Toolkit (RTK) & RTK Query API Caching prevent context window overflow during long agent sessions?
Instead of generating repetitive boilerplate across multi-turn prompts, this skill enforces strict modular patterns. The agent concisely calls createSlice and createApi with typed definitions, minimizing generated token count.
Q:Does this skill require escalated root or container permissions?
No. The skill is audited with a security score of 98/100, requiring only read/write access to the local project workspace (fs_read: true, fs_write: workspace) with zero outbound network requirements.
Ready to equip your autonomous agent with Redux Toolkit (RTK) & RTK Query API Caching?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.