queicloco-nextjs
v0.1.4
Published
This library aims to simplify the integration of Keycloak with NestJS applications. It provides a basic interface, provider and server actions to help you manage the authentication and authorization of applications
Downloads
9
Readme
queicloco-nextjs
This library aims to simplify the integration of Keycloak with NestJS applications. It provides a basic interface, provider and server actions to help you manage the authentication and authorization of applications
Installation
npm install queicloco-nextjs
Usage
1. Create a wrapper provider
Create a provider to wrap your application with the AuthProvider
component. The AuthProvider
component will manage the authentication and authorization of the application.
// providers.tsx
"use client";
import {PropsWithChildren, Suspense} from "react";
import {AuthProvider, AuthProviderProps} from "queicloco-nextjs";
const keycloakConfig = {
url: process.env.NEXT_PUBLIC_KEYCLOAK_URL!,
realm: process.env.NEXT_PUBLIC_KEYCLOAK_REALM!,
clientId: process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID!,
};
export function Providers({children}: PropsWithChildren) {
const authProps: Omit<AuthProviderProps, "children"> = {
config: keycloakConfig,
profile: (
{username, firstName, lastName, email}, //KeycloakProfile,
{realm_access, resource_access, sub} //KeycloakTokenParsed,
) => {
return {
id: sub,
username,
firstName,
lastName,
email,
realm_access,
resource_access,
};
}
,
}
;
return (
<AuthProvider {...authProps} >
<Suspense>{children} </Suspense>
</AuthProvider>
);
}
2. Create a login callback page
Create a page to handle the login callback from Keycloak. This page will be used to redirect the user to the application after the login process is completed.
// app/auth/callback/page.tsx
import { CallbackPage } from "queicloco-nextjs";
export default CallbackPage;
3-1. Use on server side
Create a server side page to get the user profile from the server side. This page will be used to get the user profile from the server side.
import { useServerAuth } from "queicloco-nextjs/server";
import Link from "next/link";
export default async function Page() {
const { profile } = await useServerAuth();
return (
<div>
Page {profile?.username}
<Link href={"/"}>Home</Link>
</div>
);
}
3-2. Use on client side
Create a client side page to get the user profile from the client side. This page will be used to get the user profile from the client side.
"use client";
import {useAuth} from "queicloco-nextjs";
import Link from "next/link";
export default function Page() {
const {profile} = useAuth();
return (
<div>
Page {profile?.username}
<Link href={"/"}>Home</Link>
</div>
);
}