π A Simple and Modern Approach to Securing Your React Apps Using Keycloak
A simple and modern approach to securing your React apps using Keycloak and an open-source helper library.
β‘ Introduction
Securing modern web applications is a top priority. Keycloak is a powerful open-source identity and access management solution, but integrating it with React can be frustrating β especially for developers who want fast, reliable, and flexible authentication.
To solve this pain point, I created an open-source library called GJC Keycloak Manager. It simplifies the integration process so that any React developer can secure their app in minutes.
π Features
- π Seamless login/logout with Keycloak
- βοΈ React Context integration
- π§βπ» Built with TypeScript
- π¦ Lightweight and tree-shakable
- π Easy setup, with full customization options
π οΈ How It Works
1. Install the library:
npm install keycloak-ease
2. Create a Keycloak config file:
export const keycloakConfig = {
url: "http://localhost:8080/auth",
realm: "your-realm-name",
clientId: "your-client-id",
};
3. Initialize Keycloak in your application:
import { initKeycloak } from "keycloak-ease";
import useSessionStore from "keycloak-ease/dist/stores/SessionStore";
import { keycloakConfig } from "./keycloak-config";
// Initialize Keycloak
const keycloak = initKeycloak(keycloakConfig);
// Initialize the session store
useSessionStore.getState().initialize(
{ onLoad: "login-required" }, // or 'check-sso'
keycloakConfig
);
4. Use the session store in your components:
import useSessionStore from "keycloak-ease/dist/stores/SessionStore";
function MyComponent() {
const { authenticated, userInfo, login, logout } = useSessionStore();
if (!authenticated) {
return <button onClick={login}>Login</button>;
}
return (
<div>
<p>Welcome, {userInfo?.name || userInfo?.email}</p>
<button onClick={logout}>Logout</button>
</div>
);
}
π Full Setup Guide
If youβre new to Keycloak or want to see how to configure everything, check out the step-by-step guide here:
π GitHub Tutorial
π‘ Why I Built This
As a full-stack developer working with microservices and secure applications, I needed a quick and reusable way to implement Keycloak authentication without repeating boilerplate code across projects.
This library was born from real-world needs β and now itβs available for others.
π Want to Contribute?
Iβd love to hear your feedback!
Feel free to:
- β Star the repository
- π₯ Open issues
- π§ͺ Suggest features
- π§ Submit pull requests
π GitHub Repo
π About the Author
Iβm Mateus Alves, a Brazilian full-stack developer passionate about clean architecture, security, and scalable solutions.
Connect with me on GitHub or LinkedIn.
β¨ Letβs Make Authentication Easier, Together.
Top comments (0)