For a large complex React Native Expo app with RTK (Redux Toolkit), here's a robust setup for authentication with signup/login:
Project Structure
src/
├── features/
│ ├── auth/
│ │ ├── authSlice.ts
│ │ ├── authApi.ts
│ │ └── authTypes.ts
│ └── user/
│ ├── userSlice.ts
│ └── userApi.ts
├── app/
│ └── store.ts
└── services/
└── api.ts
Base API Setup
// src/services/api.ts
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { RootState } from '../app/store';
const baseQuery = fetchBaseQuery({
baseUrl: process.env.EXPO_PUBLIC_API_URL,
prepareHeaders: (headers, { getState }) => {
const token = (getState() as RootState).auth.token;
if (token) {
headers.set('authorization', `Bearer ${token}`);
}
return headers;
},
});
export const api = createApi({
baseQuery,
tagTypes: ['User', 'Auth'],
endpoints: () => ({}),
});
Auth API Slice
// src/features/auth/authApi.ts
import { api } from '../../services/api';
import { LoginRequest, SignupRequest, AuthResponse } from './authTypes';
export const authApi = api.injectEndpoints({
endpoints: (builder) => ({
login: builder.mutation<AuthResponse, LoginRequest>({
query: (credentials) => ({
url: '/auth/login',
method: 'POST',
body: credentials,
}),
}),
signup: builder.mutation<AuthResponse, SignupRequest>({
query: (userData) => ({
url: '/auth/signup',
method: 'POST',
body: userData,
}),
}),
refreshToken: builder.mutation<AuthResponse, void>({
query: () => ({
url: '/auth/refresh',
method: 'POST',
}),
}),
logout: builder.mutation<void, void>({
query: () => ({
url: '/auth/logout',
method: 'POST',
}),
}),
}),
});
export const {
useLoginMutation,
useSignupMutation,
useRefreshTokenMutation,
useLogoutMutation,
} = authApi;
Auth Slice with Persistence
// src/features/auth/authSlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { authApi } from './authApi';
import { AuthState, User } from './authTypes';
const initialState: AuthState = {
user: null,
token: null,
refreshToken: null,
isAuthenticated: false,
isLoading: false,
};
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
setCredentials: (
state,
action: PayloadAction<{ user: User; token: string; refreshToken: string }>
) => {
state.user = action.payload.user;
state.token = action.payload.token;
state.refreshToken = action.payload.refreshToken;
state.isAuthenticated = true;
},
clearCredentials: (state) => {
state.user = null;
state.token = null;
state.refreshToken = null;
state.isAuthenticated = false;
},
updateUser: (state, action: PayloadAction<Partial<User>>) => {
if (state.user) {
state.user = { ...state.user, ...action.payload };
}
},
},
extraReducers: (builder) => {
// Handle login success
builder.addMatcher(
authApi.endpoints.login.matchFulfilled,
(state, { payload }) => {
state.user = payload.user;
state.token = payload.token;
state.refreshToken = payload.refreshToken;
state.isAuthenticated = true;
state.isLoading = false;
}
);
// Handle signup success
builder.addMatcher(
authApi.endpoints.signup.matchFulfilled,
(state, { payload }) => {
state.user = payload.user;
state.token = payload.token;
state.refreshToken = payload.refreshToken;
state.isAuthenticated = true;
state.isLoading = false;
}
);
// Handle logout
builder.addMatcher(
authApi.endpoints.logout.matchFulfilled,
(state) => {
state.user = null;
state.token = null;
state.refreshToken = null;
state.isAuthenticated = false;
}
);
},
});
export const { setCredentials, clearCredentials, updateUser } = authSlice.actions;
export default authSlice.reducer;
Store Configuration with Redux Persist
// src/app/store.ts
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import {
persistStore,
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from 'redux-persist';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { api } from '../services/api';
import authReducer from '../features/auth/authSlice';
const persistConfig = {
key: 'root',
storage: AsyncStorage,
whitelist: ['auth'], // Only persist auth state
};
const rootReducer = combineReducers({
[api.reducerPath]: api.reducer,
auth: authReducer,
});
const persistedReducer = persistReducer(persistConfig, rootReducer);
export const store = configureStore({
reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}).concat(api.middleware),
});
export const persistor = persistStore(store);
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
Auth Middleware for Token Refresh
// src/middleware/authMiddleware.ts
import { Middleware } from '@reduxjs/toolkit';
import { authApi } from '../features/auth/authApi';
import { clearCredentials, setCredentials } from '../features/auth/authSlice';
export const authMiddleware: Middleware = (store) => (next) => async (action) => {
// Check if action is a rejected API call due to 401
if (action.type.endsWith('/rejected') && action.payload?.status === 401) {
const state = store.getState();
const refreshToken = state.auth.refreshToken;
if (refreshToken) {
try {
const result = await store.dispatch(
authApi.endpoints.refreshToken.initiate()
).unwrap();
store.dispatch(setCredentials(result));
// Retry the original request
const originalAction = action.meta.arg.originalArgs;
store.dispatch(api.endpoints[action.meta.arg.endpointName].initiate(originalAction));
} catch (error) {
store.dispatch(clearCredentials());
}
}
}
return next(action);
};
Usage in Components
// LoginScreen.tsx
import React from 'react';
import { View, TextInput, Button, Alert } from 'react-native';
import { useLoginMutation } from '../features/auth/authApi';
import { useAppDispatch } from '../app/hooks';
export const LoginScreen = () => {
const [email, setEmail] = React.useState('');
const [password, setPassword] = React.useState('');
const [login, { isLoading }] = useLoginMutation();
const handleLogin = async () => {
try {
await login({ email, password }).unwrap();
// Navigation handled by auth state change
} catch (error) {
Alert.alert('Login Failed', error.data?.message || 'An error occurred');
}
};
return (
<View>
<TextInput
placeholder="Email"
value={email}
onChangeText={setEmail}
autoCapitalize="none"
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
<Button
title="Login"
onPress={handleLogin}
disabled={isLoading}
/>
</View>
);
};
App Entry Point
// App.tsx
import React from 'react';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistor } from './src/app/store';
import { NavigationContainer } from '@react-navigation/native';
import { RootNavigator } from './src/navigation/RootNavigator';
export default function App() {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<NavigationContainer>
<RootNavigator />
</NavigationContainer>
</PersistGate>
</Provider>
);
}
Navigation with Auth State
// src/navigation/RootNavigator.tsx
import React from 'react';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { useAppSelector } from '../app/hooks';
import { AuthNavigator } from './AuthNavigator';
import { MainNavigator } from './MainNavigator';
const Stack = createNativeStackNavigator();
export const RootNavigator = () => {
const isAuthenticated = useAppSelector((state) => state.auth.isAuthenticated);
return (
<Stack.Navigator screenOptions={{ headerShown: false }}>
{isAuthenticated ? (
<Stack.Screen name="Main" component={MainNavigator} />
) : (
<Stack.Screen name="Auth" component={AuthNavigator} />
)}
</Stack.Navigator>
);
};
This setup provides:
- Centralized API configuration with automatic token injection
- Persistent auth state across app restarts
- Automatic token refresh on 401 responses
- Type-safe Redux state management
- Clean separation of concerns
- Easy testing and maintenance
For a complex app, you might also want to add:
- Error boundary components
- Loading states management
- Deep linking support
- Biometric authentication
- Multi-factor authentication support
- Role-based access control