This guide explains how to modify the Next Identity JavaScript SDK to add custom functionality and adapt it to your specific requirements.
To get started, clone the SDK repository:
git clone https://github.com/next-reason/ni-js-oidc.git
cd ni-js-oidc
The main file handling authentication logic is next-identity-client.js
. Open it in a code editor to make modifications.
You can customize the login and logout process by updating the functions inside next-identity-client.js
.
Modify the login
function to include additional logging or redirect logic:
function login() {
console.log("Custom login process initiated");
window.location.href = `${config.authority}/authorize?client_id=${config.client_id}&redirect_uri=${config.redirect_uri}&response_type=code&scope=${config.scope}`;
}
Modify the logout
function to perform extra cleanup steps:
function logout() {
console.log("Clearing user data before logout");
localStorage.removeItem("user_token");
window.location.href = config.post_logout_redirect_uri;
}
The SDK now includes a simplified way to display user information. It will show either the user's given name or email address (whichever is available) in a designated HTML element.
Add a div with the ID user-display
to your HTML:
<div id="user-display"></div>
<div id="user-email"></div>
The SDK automatically handles:
- Displaying the user's given name in the user-display element
- Displaying the user's email in the user-email element
- Toggling login/logout button visibility based on authentication state
- Clearing user information on logout
<button id="login-button">Log In</button>
<button id="logout-button" style="display: none;">Log Out</button>
<div id="user-display"></div>
<div id="user-email"></div>
The SDK includes a registration feature that allows users to create new accounts. The registration flow uses the same parameters as login but directs users to the registration form.
To add registration functionality to your application, include a button with the ID register-button
in your HTML:
<button id="register-button">Register</button>
The SDK automatically detects this button and attaches a click event that redirects users to the registration form.
<button id="login-button">Log In</button>
<button id="logout-button" style="display: none;">Log Out</button>
<button id="register-button">Register</button>
<div id="user-display"></div>
<div id="user-email"></div>
You can also trigger registration programmatically by calling the register()
method:
document.getElementById('custom-register-btn').addEventListener('click', () => {
nextIdentity.register();
});
The SDK includes a profile editing feature that allows users to update their account information. The profile editing flow uses the same parameters as login and registration but directs users to the personal details form.
To add profile editing functionality to your application, include a button with the ID edit-profile-button
in your HTML:
<button id="edit-profile-button">Edit Profile</button>
The SDK automatically detects this button and attaches a click event that redirects users to the profile editing form.
<button id="login-button">Log In</button>
<button id="logout-button" style="display: none;">Log Out</button>
<button id="register-button">Register</button>
<button id="edit-profile-button">Edit Profile</button>
<div id="user-display"></div>
<div id="user-email"></div>
You can also trigger profile editing programmatically by calling the editProfile()
method:
document.getElementById('custom-profile-btn').addEventListener('click', () => {
nextIdentity.editProfile();
});
The SDK provides a simple method to check if the user has a valid access token:
if (nextIdentity.hasValidAccessToken()) {
// User is authenticated
console.log("User is logged in");
} else {
// User is not authenticated
console.log("User is not logged in");
}
Here's how to gate content on a page that requires authentication:
document.addEventListener('DOMContentLoaded', () => {
// Check if user has valid access token
if (!nextIdentity.hasValidAccessToken()) {
// No valid token found, redirect to homepage
window.location.href = '/index.html';
return;
}
// User is authenticated, show protected content
const protectedContent = document.getElementById('protected-content');
if (protectedContent) {
protectedContent.style.display = 'block';
}
// Optional: Load user-specific data
const accessToken = localStorage.getItem('access_token');
fetch('/api/user-data', {
headers: {
'Authorization': `Bearer ${accessToken}`
}
})
.then(response => response.json())
.then(data => {
// Process user data
console.log('User data:', data);
})
.catch(error => {
console.error('Error fetching user data:', error);
});
});
You can add a new function to enhance the SDK with additional capabilities.
Add a function to retrieve and log user information after authentication:
async function getUserInfo() {
const token = localStorage.getItem("user_token");
if (!token) {
console.log("No token found, user not logged in");
return;
}
const response = await fetch(`${config.authority}/userinfo`, {
headers: { Authorization: `Bearer ${token}` },
});
const userInfo = await response.json();
console.log("User Info:", userInfo);
return userInfo;
}
After making changes, rebuild the SDK to generate an updated version:
npm run build
To use the modified SDK in a project:
import { login, logout, getUserInfo } from './next-identity-client.js';
login();
getUserInfo();
logout();
Run the development server to test your changes:
npm run dev
This will allow you to verify that your modifications work as expected before deploying.
To publish your modified SDK:
- Commit and push your changes to a repository.
- If using a CDN, upload the modified
next-identity-client.js
. - If publishing to npm, update
package.json
and run:
npm publish
With these steps, you can fully customize the Next Identity JavaScript SDK to fit your authentication needs.