npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ssr-keycloak

v1.0.1

Published

SSR compatible Keycloak authentication library for React applications

Downloads

20

Readme

SSR Keycloak

SSR (Server-Side Rendering) uyumlu Keycloak authentication kütüphanesi. Next.js ile tam entegrasyon sağlar ve server-side session yönetimi ile cookie tabanlı authentication sunar.

Özellikler

  • SSR Uyumlu: Server-side rendering ile tam uyumlu
  • Cookie Tabanlı Session: Güvenli server-side session yönetimi
  • Authorization Code Flow: OAuth 2.0 Authorization Code Flow desteği
  • PKCE Desteği: Proof Key for Code Exchange (PKCE) güvenliği
  • Next.js Middleware: Next.js middleware entegrasyonu
  • React Hooks: Kolay kullanım için React hooks
  • TypeScript: Tam TypeScript desteği
  • Auto Token Refresh: Otomatik token yenileme
  • Role-Based Access: Rol tabanlı erişim kontrolü

Kurulum

npm install ssr-keycloak

Hızlı Başlangıç

1. Keycloak Konfigürasyonu

// lib/keycloak.ts
import { KeycloakConfig } from 'ssr-keycloak';

export const keycloakConfig: KeycloakConfig = {
  url: process.env.KEYCLOAK_URL || 'http://localhost:8080/auth',
  realm: process.env.KEYCLOAK_REALM || 'your-realm',
  clientId: process.env.KEYCLOAK_CLIENT_ID || 'your-client-id',
  clientSecret: process.env.KEYCLOAK_CLIENT_SECRET,
  redirectUri: process.env.KEYCLOAK_REDIRECT_URI || 'http://localhost:3000/auth/callback',
  postLogoutRedirectUri: process.env.KEYCLOAK_POST_LOGOUT_REDIRECT_URI || 'http://localhost:3000'
};

2. Next.js Middleware

// middleware.ts
import { createKeycloakMiddleware } from 'ssr-keycloak';
import { keycloakConfig } from './lib/keycloak';

export default createKeycloakMiddleware(keycloakConfig, {
  protectedRoutes: ['/admin', '/dashboard'],
  publicRoutes: ['/login', '/register'],
  loginRoute: '/login',
  redirectToLogin: true
});

export const config = {
  matcher: [
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
};

3. API Routes

// app/api/auth/session/route.ts
import { createKeycloakAPIRoutes } from 'ssr-keycloak';
import { keycloakConfig } from '@/lib/keycloak';

const apiRoutes = createKeycloakAPIRoutes(keycloakConfig);

export async function GET() {
  return apiRoutes.sessionHandler();
}

export async function POST() {
  return apiRoutes.loginHandler();
}
// app/api/auth/callback/route.ts
import { KeycloakAuthHandler } from 'ssr-keycloak';
import { keycloakConfig } from '@/lib/keycloak';
import { NextRequest, NextResponse } from 'next/server';

const authHandler = new KeycloakAuthHandler(keycloakConfig);

export async function GET(request: NextRequest) {
  const requestContext = {
    cookies: Object.fromEntries(request.cookies.getAll().map(c => [c.name, c.value])),
    headers: Object.fromEntries(request.headers.entries()),
    url: request.url,
    method: request.method
  };

  const response = NextResponse.next();
  const responseContext = {
    setCookie: (cookie: any) => {
      response.cookies.set(cookie.name, cookie.value, {
        expires: cookie.expires,
        maxAge: cookie.maxAge,
        domain: cookie.domain,
        path: cookie.path,
        secure: cookie.secure,
        httpOnly: cookie.httpOnly,
        sameSite: cookie.sameSite
      });
    },
    deleteCookie: (name: string) => {
      response.cookies.delete(name);
    },
    redirect: (url: string) => {
      return NextResponse.redirect(new URL(url, request.url));
    },
    json: (data: any) => {
      return NextResponse.json(data);
    }
  };

  await authHandler.handleCallback(requestContext, responseContext);
  return response;
}

4. React Provider

// app/layout.tsx
import { KeycloakProvider } from 'ssr-keycloak';
import { keycloakConfig } from '@/lib/keycloak';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <KeycloakProvider config={keycloakConfig}>
          {children}
        </KeycloakProvider>
      </body>
    </html>
  );
}

5. Component Kullanımı

// components/Header.tsx
'use client';
import { useKeycloak } from 'ssr-keycloak';

export default function Header() {
  const { 
    isAuthenticated, 
    user, 
    login, 
    logout, 
    isLoading 
  } = useKeycloak();

  if (isLoading) {
    return <div>Loading...</div>;
  }

  return (
    <header>
      {isAuthenticated ? (
        <div>
          <span>Welcome, {user?.username}!</span>
          <button onClick={() => logout()}>Logout</button>
        </div>
      ) : (
        <button onClick={() => login()}>Login</button>
      )}
    </header>
  );
}

API Referansı

Hooks

useKeycloak()

Ana hook, tüm authentication fonksiyonlarını sağlar.

const {
  isAuthenticated,
  user,
  tokens,
  session,
  isLoading,
  error,
  login,
  logout,
  refreshToken,
  updateToken,
  hasRole,
  hasAnyRole,
  hasAllRoles,
  getUserRoles
} = useKeycloak();

useKeycloakSession()

Sadece session bilgileri için.

const { session, isAuthenticated, isLoading } = useKeycloakSession();

useKeycloakUser()

Sadece kullanıcı bilgileri için.

const { user, isAuthenticated, isLoading } = useKeycloakUser();

useKeycloakAuth()

Sadece authentication fonksiyonları için.

const { login, logout, refreshToken, updateToken } = useKeycloakAuth();

useKeycloakRoles()

Sadece rol kontrolleri için.

const { hasRole, hasAnyRole, hasAllRoles, getUserRoles } = useKeycloakRoles();

Server-Side Functions

getSessionFromRequest(request)

Request'ten session bilgilerini alır.

setSessionInResponse(session, response)

Session'ı response'a yazar.

clearSessionInResponse(response)

Session'ı response'dan siler.

isSessionValid(session)

Session'ın geçerli olup olmadığını kontrol eder.

Middleware Configuration

const middlewareConfig = {
  protectedRoutes: ['/admin', '/dashboard'], // Korumalı route'lar
  publicRoutes: ['/login', '/register'],     // Herkese açık route'lar
  loginRoute: '/login',                      // Login sayfası
  redirectToLogin: true,                     // Login'e yönlendir
  cookieName: 'ssr_keycloak_session',        // Cookie adı
  cookieSecret: 'your-secret'                // Cookie şifreleme anahtarı
};

Environment Variables

KEYCLOAK_URL=http://localhost:8080/auth
KEYCLOAK_REALM=your-realm
KEYCLOAK_CLIENT_ID=your-client-id
KEYCLOAK_CLIENT_SECRET=your-client-secret
KEYCLOAK_REDIRECT_URI=http://localhost:3000/auth/callback
KEYCLOAK_POST_LOGOUT_REDIRECT_URI=http://localhost:3000
KEYCLOAK_SESSION_SECRET=your-session-secret

Güvenlik

  • Session'lar şifrelenmiş cookie'lerde saklanır
  • PKCE (Proof Key for Code Exchange) desteği
  • HttpOnly cookie'ler XSS saldırılarına karşı koruma
  • Secure cookie'ler HTTPS üzerinde çalışır
  • SameSite cookie'ler CSRF saldırılarına karşı koruma

Lisans

MIT

Geliştirici

Murat Resuloğulları - MG-Software