Hackforge Academy

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 />;
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community