Integrating Keycloak with a Next.js Frontend and Securing API Calls via Kong API Gateway
In an era of increasing reliance on APIs and microservices, securing communication between clients and backend services has become a…
Integrating Keycloak with a Next.js Frontend and Securing API Calls via Kong API Gateway

In an era of increasing reliance on APIs and microservices, securing communication between clients and backend services has become a critical challenge. Microservice architectures, with their distributed nature, demand robust solutions for managing authentication and authorization across multiple services.
API Gateways like Kong play a pivotal role in this ecosystem by centralizing API traffic management, ensuring scalability, and enhancing security. However, to achieve secure and seamless access control, an identity provider is essential. This is where Identity Providers like Keycloak come in.
Keycloak, an open-source identity and access management solution, integrates seamlessly with Kong to handle user authentication, token issuance, and fine-grained authorization.
By delegating identity and access management to Keycloak and leveraging Kong’s OpenID Connect (OIDC) plugin for API protection, developers can ensure a consistent and secure authentication flow across services, adhering. This ensures consistency in a micro-services architecture to principles like single use responsibility, and help to loosely couple the identity services as its own service interface.

In this guide, we’ll dive deep into integrating Keycloak with a Next.js frontend application using the Keycloak JavaScript adapter. Additionally, we’ll demonstrate how to secure subsequent API calls using Kong API Gateway’s OpenID Connect (OIDC) plugin. This integration ensures robust user authentication and fine-grained API authorization by leveraging modern identity standards.
Key Concepts Behind the Integration
Before we delve into the setup, let’s break down the key components and their roles in the integration:
- Keycloak: An open-source identity and access management solution that supports OAuth 2.0, OpenID Connect (OIDC), and SAML. It acts as the identity provider (IdP) in this setup.
- Next.js Frontend: A React-based framework that serves as the user interface, integrated with Keycloak using the Keycloak JavaScript adapter.
- Kong API Gateway: A powerful API management tool that secures backend services by enforcing authentication and authorization using the OIDC plugin.
Workflow Overview
- User Authentication: The Next.js frontend uses the Keycloak JS adapter to handle user login and token management.
- Token Issuance: After successful authentication, Keycloak issues an ID token and access token.
- API Request Security: The access token is passed to Kong with each API request, where Kong validates the token’s authenticity and enforces access controls.
- Authorization: Kong uses group claims from the token to allow or deny access to specific resources.
Setting Up Keycloak
Step 1: Start Keycloak
Use Docker Compose to launch Keycloak:
docker-compose up
Access the Keycloak admin console at http://localhost:7080 and log in using the following credentials:
- Username:
admin - Password:
admin
Step 2: Create a Realm
- Navigate to the admin console.
- Create a new realm called
kong-frontend. A realm in Keycloak represents a namespace for managing users, credentials, roles, and clients.
Step 3: Configure a Client
- Under the
kong-frontendrealm, create a client namedkong-frontend. - Update the client settings:
- Set
Access Typetoconfidential. - Ensure
Valid Redirect URIsinclude a trailing slash, e.g.,[http://localhost:3001/*.](http://localhost:3001/*.) - Save the changes.
Step 4: Create a User
- Navigate to the Users section and create a new user.
- Set a username and save the user.
- Under the user’s Credentials tab, set a password and toggle the “Temporary” option to “Off”.
Setting Up the Next.js Frontend
Step 1: Install Dependencies
To use Keycloak with your Next.js app, install the necessary libraries:
npm install keycloak-js @react-keycloak/web
Step 2: Configure Keycloak in the App
- Create a
keycloak.jsfile to configure Keycloak:
import Keycloak from 'keycloak-js';
const keycloakConfig = {
url: 'http://localhost:7080/auth',
realm: 'kong-frontend',
clientId: 'kong-frontend',
};
const keycloak = new Keycloak(keycloakConfig);
export default keycloak;
Wrap your app with the Keycloak provider in _app.js:
import { ReactKeycloakProvider } from '@react-keycloak/web';
import keycloak from '../keycloak';
function MyApp({ Component, pageProps }) {
return (
<ReactKeycloakProvider authClient={keycloak}>
<Component {...pageProps} />
</ReactKeycloakProvider>
);
}
export default MyApp;
Step 3: Start the Application
Run your Next.js app:
npm run dev
The app should be accessible at http://localhost:3001. Users can log in via Keycloak, and tokens are managed automatically by the adapter.
Setting Up Kong API Gateway
Step 1: Configure the OpenID Connect Plugin
- Create a Kong service and route for your API. Follow these steps here to do so.
- Add the OIDC plugin to the route:
- In settings, set the Common -> Issuer to Keycloak’s discovery endpoint:
[http://keycloak:7080/realms/kong-frontend](http://keycloak:7080/realms/kong-frontend)
- Update the OIDC plugin’s following settings to bypass localhost-related issues:
- Advanced Settings -> Introspection endpoint:
[http://keycloak:7080/realms/kong-frontend/protocol/openid-connect/token/introspect](http://keycloak:7080/realms/kong-frontend/protocol/openid-connect/token/introspect) - Advanced Settings -> JWKS endpoint:
[http://keycloak:7080/realms/kong-frontend/protocol/openid-connect/certs](http://keycloak:7080/realms/kong-frontend/protocol/openid-connect/certs) - Common -> Enable
IntrospectionandBearer Access Tokenauthentication methods.
Execution: Authentication Flow
- Navigate to
http://localhost:3001and log in using the Keycloak credentials. - Retrieve the access token from the Keycloak adapter (stored in the frontend state).
- Use the access token to authenticate API requests by including it in the
Authorizationheader.
Example cURL command:
curl -X GET http://localhost:8000/api \
-H "Authorization: Bearer <ACCESS_TOKEN>"
Kong validates the token’s signature and introspects its claims to ensure it’s valid.
Adding Authorization with Keycloak Groups
Step 1: Configure Groups in Keycloak
- Navigate to Groups in your realm and create a group called
developers. - Add the user to this group.
Step 2: Map Groups to Tokens
- Navigate to
Client Scopes > profile > Mappers > Create. - Configure the mapper as follows:
- Name:
groups - Token Claim Name:
groups - Include in token: Yes
Step 3: Update the OIDC Plugin in Kong
- Under the OIDC plugin’s Authorization section:
- Add
groupsto theAuthenticated Groups Claimfield.
Step 4: Add the ACL Plugin
- Add an ACL plugin at the route level.
- Configure the plugin:
- config.deny:
developers - Enable
Always Use Authenticated Groups - Save the configuration.
Execution: Authorization Flow
- Log in to the frontend app and retrieve a new access token.
- Verify the token on jwt.io to ensure the
groupsclaim is present. - Test the API with the token:
Example:
curl -X GET http://localhost:8000/api \
-H "Authorization: Bearer <ACCESS_TOKEN>"
- Modify the ACL plugin settings:
- When
developersis inconfig.deny, the response is403 Unauthorized. - When
developersis inconfig.allow, the response is200 OK.
How It Works
User Authentication
- The frontend app initializes Keycloak using the adapter, which handles the login process and manages tokens.
- Keycloak issues tokens after successful authentication.
API Protection
- The OIDC plugin in Kong verifies the token’s validity via introspection or JWKS.
- Tokens are used to enforce authentication and authorization at the gateway level.
Group-Based Authorization
- Group claims in tokens allow Kong to enforce fine-grained access control based on user roles.
- ACL and OIDC plugins work together to allow or deny access to API routes.
Key Insights and Conclusion
This integration between Keycloak, Next.js, and Kong highlights several key benefits and insights that developers and organizations can leverage:
Seamless Authentication Workflow:
- Keycloak’s JavaScript adapter simplifies user authentication by managing login states and token lifecycles on the frontend. This minimizes development complexity while ensuring secure access to the application.
Centralized Identity Management:
- Using Keycloak as an identity provider enables organizations to centralize user management, making it easier to implement consistent policies for login, password management, and role assignments across multiple applications.
API Security with Kong:
- Kong’s OIDC plugin provides robust mechanisms to secure APIs by validating tokens issued by Keycloak. Features like introspection and JWKS endpoint support make it highly adaptable to different environments and configurations.
Fine-Grained Authorization:
- The combination of Keycloak’s group claims and Kong’s ACL plugin allows precise control over who can access specific API routes. This is particularly valuable for implementing role-based access control (RBAC) in modern applications.
Scalability and Statelessness:
- Leveraging JWT tokens ensures a stateless authentication system, which is essential for scalability in distributed systems. Kong’s lightweight validation mechanisms enhance performance by offloading complex authorization logic from backend services.
Future-Proof Security:
- By adopting open standards like OAuth 2.0 and OpenID Connect, this setup ensures compatibility with other identity providers and API gateways, making it a sustainable choice for evolving application ecosystems.
Conclusion
This guide demonstrates the integration between Keycloak and Kong to build secure, scalable, and user-friendly applications. By using Keycloak for identity management and Kong for API protection, such allows applications to scale via a platform approach.
This decoupling of any operational logic around authentication and traffic management from the application code itself, increasing the time to market for new applications and features.
메타데이터
- post_id
- dabd9d691f5c
- slug
- integrating-keycloak-with-a-next-js-frontend-and-securing-api-calls-via-kong-api-gateway-dabd9d691f5c
- url
- https://medium.com/@eugenetan_91090/integrating-keycloak-with-a-next-js-frontend-and-securing-api-calls-via-kong-api-gateway-dabd9d691f5c
- canonical_url
- https://medium.com/@eugenetan_91090/integrating-keycloak-with-a-next-js-frontend-and-securing-api-calls-via-kong-api-gateway-dabd9d691f5c
- author_url
- https://medium.com/@eugenetan_91090
- status
- ok
- fetched_at
- 2026-06-20 20:29:01