Protect API Routes
Secure your endpoints by learning how to use authentication middleware to protect API routes from unauthenticated access.
In this section, you will configure your existing auth middleware to automatically protect API routes.
Add Protected APIs to Auth Middleware
Modify the requireAuth settings inside src/wristband.ts to specify your protected API routes:
// src/wristband.ts
// ...
export const requireAuth = wristbandAuth.createMiddlewareAuth({
authStrategies: ['SESSION'],
sessionConfig: {
sessionOptions,
sessionEndpoint: '/api/auth/session'
},
protectedPages: ['/', '/dashboard', '/settings(.*)'],
protectedApis: [
'/api/v1/orders', // Protects only /api/v1/orders route
'/api/v1/products/(.*)', // Protects all /api/v1/products/* routes
],
});Unauthenticated requests to protected API routes will now automatically receive a 401 Unauthorized response.
Manual API Route Protection (Optional)
For endpoints that need custom authentication logic or precise access control, you can validate the session manually within your API route handler rather than using middleware.
Note: Middleware protection alone is typically sufficient for most use cases.
// src/pages/api/v1/orders.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { getSession } from 'src/wristband';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const session = await getSession(req, res);
// Return 401 if not authenticated
if (!session.isAuthenticated) {
return res.status(401).json({ error: 'Unauthorized' });
}
// Your API logic here using session data
return res.status(200).json({
message: 'Order data retrieved',
userId: session.userId,
tenantId: session.tenantId,
});
}Handling 401 Responses in Frontend Code
When your frontend sends requests to API routes protected by the requireAuth middleware, it may receive the following error response:
401 Unauthorized: This response will be returned if the session is missing or invalid.
To ensure a smooth user experience, configure your frontend to catch and process this error gracefully. Review the common patterns below to see how to handle 401 responses effectively in your JavaScript application.
Pattern 1: Use an Axios Interceptor
For applications using Axios, set up a response interceptor to handle 401 error responses automatically. In the following example, the interceptor catches the error and redirects the user to the Login Endpoint to re-authenticate.
import axios from 'axios';
import { redirectToLogin } from '@wristband/react-client-auth';
const apiClient = axios.create({
baseURL: '<backend-apis-base-url>',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
withCredentials: true,
});
// If a 401 response is detected, redirect the user to your Login Endpoint.
const unauthorizedAccessInterceptor = (error: unknown) => {
if (axios.isAxiosError(error) && error.response?.status === 401) {
redirectToLogin('<your-login-endpoint-url>');
return;
}
return Promise.reject(error);
};
apiClient.interceptors.response.use(undefined, unauthorizedAccessInterceptor);
export { apiClient };
Pattern 2: Explicitly Catch Errors When Making API Calls
If you need tighter control over your error logic, catch 401 responses directly within your API call routines. Doing this enables you to build custom error-handling workflows on a per-endpoint basis rather than relying on a global catch-all.
import axios from 'axios';
import { redirectToLogin } from '@wristband/react-client-auth';
async function executeApiCall() {
try {
const response = await axios.get('<your-server-api-url>');
alert('Success!');
} catch (error: unknown) {
if (axios.isAxiosError(error) && error.response?.status === 401) {
redirectToLogin('<your-login-endpoint-url>');
} else {
console.error('Unexpected error:', error);
alert('Something went wrong!');
}
}
}
import { redirectToLogin } from '@wristband/react-client-auth';
function getCookie(name: string): string | null {
const match = document.cookie.match(new RegExp('(^|;\\s*)' + name + '=([^;]*)'));
return match ? decodeURIComponent(match[2]) : null;
}
async function executeApiCall() {
const csrfToken = getCookie('CSRF-TOKEN');
try {
const response = await fetch('/api/protected-endpoint', {
credentials: 'include',
headers: {
'X-CSRF-TOKEN': csrfToken ?? ''
}
});
if (!response.ok) {
if (response.status === 401 || response.status === 403) {
redirectToLogin('<your-login-endpoint-url>');
return;
}
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, Message: ${errorText}`);
}
...
} catch (error) {
...
}
}Updated 8 days ago
What’s Next
Your frontend and backend should now have proper authentication checks in place. Let's run some final tests to ensure everything is working.