Category: react
aws cognito add authentication to react
Published on 15 Sep 2026
Explanation
Amazon Cognito provides user authentication and authorization features. React applications can use Cognito for registration, login, password recovery, and token-based access.
Code:
Common Cognito features: - User registration - User login - Email verification - Password reset - Access and ID tokens
Explanation
The AWS Amplify library provides frontend helpers for interacting with Cognito. Install the required package before adding authentication to a React project.
Code:
npm install aws-amplify
Explanation
Configure the Amplify library with the Cognito resources created in your AWS environment. The exact configuration depends on the Amplify version and project setup.
Code:
import { Amplify } from 'aws-amplify';
import outputs from './amplify_outputs';
Amplify.configure(outputs);
Explanation
A login form collects the user's identifier and password. The authentication library sends the credentials to Cognito and returns an authenticated session when successful.
Code:
const handleLogin = async () => {
try {
await signIn({ username, password });
console.log('Login successful');
} catch (error) {
console.error(error);
}
};
Explanation
Protected routes should render private content only after checking whether the user has a valid authenticated session. Redirect unauthenticated users to the login page.
Code:
function ProtectedPage({ isAuthenticated }) {
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return <Dashboard />;
}