Redux & RTK Query with Next.js (App Router)
Modern Next.js apps combine Server Components for data-heavy UI with Client Components for interactivity. For cross-route state management (e.g., auth, cart, settings) and API data with caching, Redux Toolkit (RTK) + RTK Query offers a clean, batteries-included solution.
This guide covers using Next.js App Router, TypeScript, and RTK Query with tag-based invalidation, optimistic updates, and production-ready defaults.
1. Install & Scaffold
# If you don't have a Next.js app yet
npx create-next-app@latest my-app --ts
# Inside your project
cd my-app
npm i @reduxjs/toolkit react-redux
RTK Query is included in @reduxjs/toolkit—no extra package required.
2. Suggested Project Structure
/app
layout.tsx
page.tsx
/posts
page.tsx
/features
/counter
counterSlice.ts
/lib
api.ts # RTK Query API slice
store.ts # configureStore
Providers.tsx # Redux Provider wrapper (client component)
/types
post.ts
3. Configure the Store
/lib/store.ts
import { configureStore } from "@reduxjs/toolkit";
import { api } from "./api";
import counterReducer from "@/features/counter/counterSlice"; // Optional example slice
export const store = configureStore({
reducer: {
counter: counterReducer,
[api.reducerPath]: api.reducer,
},
middleware: (getDefault) => getDefault().concat(api.middleware),
devTools: process.env.NODE_ENV !== "production",
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
Always register api.reducer and add api.middleware.
4. Wrap the App with a Redux Provider (Client Component)
/lib/Providers.tsx
"use client";
import { Provider } from "react-redux";
import { store } from "./store";
export default function Providers({ children }: { children: React.ReactNode }) {
return <Provider store={store}>{children}</Provider>;
}
/app/layout.tsx
import type { Metadata } from "next";
import Providers from "@/lib/Providers";
import "./globals.css";
export const metadata: Metadata = {
title: "Redux + RTK Query with Next.js",
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<Providers>{children}</Providers>
</body>
</html>
);
}
The Provider must be in a client component—hence the separate Providers.tsx.
5. Define Types
/types/post.ts
export type Post = {
id: string;
title: string;
body: string;
};
6. Create the RTK Query API Slice
/lib/api.ts
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import type { Post } from "@/types/post";
import type { RootState } from "./store";
export const api = createApi({
reducerPath: "api",
baseQuery: fetchBaseQuery({
baseUrl: process.env.NEXT_PUBLIC_API_URL ?? "/api",
credentials: "include",
prepareHeaders: (headers, { getState }) => {
// Optional: Attach auth token from Redux state if present
const token = (getState() as RootState as any)?.auth?.token;
if (token) headers.set("authorization", `Bearer ${token}`);
return headers;
},
}),
tagTypes: ["Posts", "Post"],
endpoints: (builder) => ({
getPosts: builder.query<Post[], void>({
query: () => "/posts",
providesTags: (result) =>
result
? [
{ type: "Posts", id: "LIST" },
...result.map((p) => ({ type: "Post" as const, id: p.id })),
]
: [{ type: "Posts", id: "LIST" }],
refetchOnFocus: true,
refetchOnReconnect: true,
keepUnusedDataFor: 60,
}),
addPost: builder.mutation<Post, Pick<Post, "title" | "body">>({
query: (body) => ({ url: "/posts", method: "POST", body }),
invalidatesTags: [{ type: "Posts", id: "LIST" }],
}),
updatePost: builder.mutation<Post, Partial<Post> & Pick<Post, "id">>({
query: ({ id, ...patch }) => ({
url: `/posts/${id}`,
method: "PATCH",
body: patch,
}),
invalidatesTags: (_res, _err, { id }) => [{ type: "Post", id }],
}),
deletePost: builder.mutation<{ success: boolean; id: string }, string>({
query: (id) => ({ url: `/posts/${id}`, method: "DELETE" }),
invalidatesTags: (_res, _err, id) => [
{ type: "Post", id },
{ type: "Posts", id: "LIST" },
],
// Optimistic update for snappy UI
async onQueryStarted(id, { dispatch, queryFulfilled }) {
const patch = dispatch(
api.util.updateQueryData("getPosts", undefined, (draft) => {
const idx = draft.findIndex((p) => p.id === id);
if (idx !== -1) draft.splice(idx, 1);
})
);
try {
await queryFulfilled;
} catch {
patch.undo();
}
},
}),
}),
});
export const {
useGetPostsQuery,
useAddPostMutation,
useUpdatePostMutation,
useDeletePostMutation,
} = api;
Tags and invalidatesTags enable automatic cache updates. Optimistic updates keep the UI responsive and rollback on error.
7. Use in a Client Component Page
/app/posts/page.tsx
"use client";
import {
useGetPostsQuery,
useAddPostMutation,
useDeletePostMutation,
} from "@/lib/api";
import { useState } from "react";
export default function PostsPage() {
const { data: posts, isLoading, isError, refetch } = useGetPostsQuery();
const [addPost, { isLoading: adding }] = useAddPostMutation();
const [delPost] = useDeletePostMutation();
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
if (isLoading) return <p>Loading…</p>;
if (isError)
return (
<p>
Something went wrong.{" "}
<button onClick={() => refetch()}>Retry</button>
</p>
);
return (
<main className="max-w-2xl mx-auto p-6 space-y-6">
<h1 className="text-2xl font-semibold">Posts</h1>
<form
className="space-y-2"
onSubmit={async (e) => {
e.preventDefault();
if (!title.trim() || !body.trim()) return;
await addPost({ title, body }).unwrap();
setTitle("");
setBody("");
}}
>
<input
className="w-full border p-2 rounded"
placeholder="Title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<textarea
className="w-full border p-2 rounded"
placeholder="Body"
value={body}
onChange={(e) => setBody(e.target.value)}
/>
<button
className="px-3 py-2 rounded bg-black text-white disabled:opacity-50"
disabled={adding}
>
{adding ? "Adding…" : "Add Post"}
</button>
</form>
<ul className="space-y-3">
{posts?.map((p) => (
<li
key={p.id}
className="border p-3 rounded flex items-start justify-between gap-4"
>
<div>
<h2 className="font-medium">{p.title}</h2>
<p className="text-sm text-gray-600">{p.body}</p>
</div>
<button
className="text-red-600"
onClick={() => delPost(p.id)}
title="Delete"
>
Delete
</button>
</li>
))}
</ul>
</main>
);
}
8. Common Pitfalls & Pro Tips
- Server vs Client: RTK Query hooks run in Client Components. Keep API-driven UI logic client-side; if mixing, pass server-fetched props down.
- Base URL: Use
NEXT_PUBLIC_API_URLfor environment flexibility (dev/stage/prod). - Auth: Use
prepareHeadersto attach tokens from Redux state. - Cache Tuning:
keepUnusedDataFor,refetchOnFocus, andrefetchOnReconnectbalance freshness vs. bandwidth. - Invalidation Pattern: Use a
LISTtag + per-entity tags for precise updates. - Optimistic UI: Patch cached queries with
api.util.updateQueryData.
9. Optional: SSR/Hydration
For SSR with Redux state, consider next-redux-wrapper. For most apps, keeping RTK Query client-only is simpler and fast due to caching.
10. Final Checklist
configureStoreincludesapi.reducerandapi.middleware.Provideris in a client wrapper.- Tag types are used consistently.
- Errors are handled with
unwrap()or UI guards. - Environment-aware base URL and credentials are set.
Happy shipping! 🚀
