This README outlines the implementation details of passing JWT tokens in a React application using React Router. This is crucial for managing access controls and secure communication between the client and server.
The application utilizes React Router for navigation and Auth0 for authentication. The main focus is on how to effectively pass JWT tokens retrieved from Auth0 to various components and routes.
- React W/ TypeScript
- Auth0
- React Router
- React Query (example)
main.tsx
: Entry point for application, setups up React DOM.app.router.tsx
: Contains routing logic and token management.auth/
: Directory containing authentication components and logic.games/
: Directory for game-related components and routing.
Below are some key code snippets to showcase how JWT tokens are passed to routes and used in the loader function:
const [token, setToken] = useState<string>(); // State to hold the JWT token
useEffect(() => {
const fetchToken = async () => {
const accessToken = await auth0.getAccessTokenSilently();
setToken(accessToken);
};
fetchToken();
}, [auth0]);
const authenticatedRoutes = useMemo(() => {
if (!token) {
return []; // No routes if no token
}
return [
featureRouter(token), // Passing the token to a feature's router
// Additional authenticated routes can be added here
];
}, [token]);
In this hypothetical example, featureRouter
might use the token as follows:
export const featureRouter = (token) => ({
path: 'feature',
element: <FeatureComponent />,
loader: async () => {
const response = await fetch('/api/data', {
headers: { Authorization: `Bearer ${token}` } // Use the token for API requests
});
return response.json();
},
children: [
// Child routes can also be protected using the token
]
});
- Authentication: The application uses
useAuth0
to handle user authentication via Auth0's React SDK. - Token Management: A JWT token is fetched and stored using React's state management. It is then passed to routes requiring authentication.
- Route Configuration: Routes are conditionally rendered based on the presence of a valid JWT token, ensuring that secure content is only available to authenticated users.
This setup provides a robust framework for handling JWT tokens in a React application, enhancing security and ensuring that sensitive information remains protected.