Reputation: 27
I'm building a Next.js application and I have implemented a custom registration page for users. I want to use Keycloak-js to handle user registration directly within the Next.js app, allowing for a seamless user experience without redirecting them to the Keycloak login and registration pages.
I’ve read through the Keycloak JavaScript Adapter documentation (https://www.keycloak.org/securing-apps/javascript-adapter) and also checked out some solutions on Stack Overflow (How to use Keycloak for user self-registration), but I couldn't find code examples showing how to implement this.
I'm trying to implement a self-registration flow with Keycloak without using administrator credentials to call the REST API for user creation. I would like the registration request to be unauthenticated, so that Keycloak itself can handle the self-registration, including sending a verification email to the user.
The following code is used to start the keycloak settings in the frontend but now I need to send the request with the user information, which is not clear in the documentation.
const keycloak = new Keycloak({
url: "http://localhost:8081",
realm: "AppName",
clientId: "appname-web"
});
Could anyone provide guidance or examples on how to use the Keycloak API (with Keycloak.js or alternatives) to register users directly from a custom Next.js page?
Upvotes: 1
Views: 231
Reputation: 69
For a custom user registration flow with Keycloak directly, you can use Keycloaks Direct Grant API along with a custom registration form to create users (by self registeration).
Step 1: Enable Self-Registration in Keycloak
Log into Keycloak Admin Console (e.g for local enviourment: http://localhost:8081/admin).
Go to Realm Settings -> Login.
Enable User Registration and Email Verification (optional - if you want users to verify via email).
Ensure that your client (i.e. appname-web) has Direct access grants enabled under the Clients -> Settings.
Step 2: Implement the Custom Registration Page in Next.js
You’ll create a form where users can enter their registration details. This page will make a request to Keycloak’s Direct Grant API endpoint to create the user.
For this first create a registration form component:
import { useState } from 'react';
export default function RegisterForm() {
const [formData, setFormData] = useState({
username: '',
password: '',
email: '',
firstName: '',
lastName: '',
});
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch('/api/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (response.ok) {
alert('Registration successful! check your email to verify');
} else {
const errorData = await response.json();
alert(`Error Message!`);
}
} catch (error) {
console.error('Error Message!);
}
};
return (
/* Implementation of form */
);
}
Then create the Next.js API Route for Registration:
try {
const response = await fetch(`${process.env.KEYCLOAK_URL}/auth/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/registrations`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.KEYCLOAK_CLIENT_SECRET}`,
},
body: JSON.stringify({
username,
credentials: [{ type: 'password', value: password }],
email,
firstName,
lastName,
enabled: true,
}),
});
Also, your env's must be set correctly:
KEYCLOAK_URL=http://localhost:8081 KEYCLOAK_REALM=AppName
KEYCLOAK_CLIENT_ID=appname-web
And then obviously call your Registeration component
Step 3: Test the Registration Flow Start your Next.js app and (on Postman or any other tool) go to
/register
to test user registration.
Important Note: In my Keycloak environment, I usually enable email verification, so be sure to configure the email settings in Keycloak properly if you want to send verification emails.
Feel free to ask if you need further assistance! :)
Upvotes: 1