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

@personql/nextjs

v1.0.7

Published

PersonQL SDK optimized for Next.js applications

Readme

PersonQL Next.js SDK

A comprehensive Next.js SDK for PersonQL authentication, user management, and Customer Data Platform (CDP) with automatic digital fingerprinting.

🎯 Why a Dedicated Next.js SDK?

While Next.js can use our existing React SDK, this dedicated Next.js SDK provides:

Automatic SSR/Hydration Handling

  • No client/server state mismatches
  • Seamless authentication state across server and client
  • Prevents hydration errors

Built-in Route Protection

  • Middleware-based authentication
  • Automatic redirects for protected routes
  • Role-based access control

Server Components Support

  • Full Next.js 13+ App Router integration
  • Server-side user data fetching
  • Optimized performance

Advanced Session Management

  • Unified session across client/server
  • Automatic token refresh
  • Secure cookie handling

🚀 Quick Start

Installation

npm install @personql/nextjs

Basic Setup

// app/layout.tsx
import { PersonQLProvider } from '@personql/nextjs';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <PersonQLProvider
          apiKey={process.env.NEXT_PUBLIC_PERSONQL_API_KEY!}
        >
          {children}
        </PersonQLProvider>
      </body>
    </html>
  );
}

// All requests will use the gateway-worker URL automatically.

Automatic Route Protection

// middleware.ts
import { createAuthMiddleware } from '@personql/nextjs';

export const middleware = createAuthMiddleware({
  apiKey: process.env.PERSONQL_API_KEY!,
  publicRoutes: ['/', '/about', '/contact'],
  authRoutes: ['/login', '/signup'],
});

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

Server Components

// app/profile/page.tsx
import { getServerUser } from '@personql/nextjs';
import { redirect } from 'next/navigation';

export default async function ProfilePage() {
  const user = await getServerUser();

  if (!user) {
    redirect('/login');
  }

  return (
    <div>
      <h1>Welcome, {user.name}!</h1>
      <p>Email: {user.email}</p>
    </div>
  );
}

Client Components

// components/UserProfile.tsx
'use client';
import { usePersonQLNext } from '@personql/nextjs';

export function UserProfile() {
  const { user, isAuthenticated, isHydrated, trackEvent } = usePersonQLNext();

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

  const handleProfileUpdate = async () => {
    await trackEvent('Profile Updated', { userId: user?.id });
  };

  return (
    <div>
      {isAuthenticated ? (
        <div>
          <h2>Hello, {user?.name}</h2>
          <button onClick={handleProfileUpdate}>Update Profile</button>
        </div>
      ) : (
        <div>Please log in</div>
      )}
    </div>
  );
}

📚 Key Features

1. SSR-Safe Authentication

import { usePersonQLNext } from '@personql/nextjs';

function MyComponent() {
  const { user, isAuthenticated, isHydrated } = usePersonQLNext();

  // Prevents hydration mismatches
  if (!isHydrated) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      {isAuthenticated ? `Welcome ${user.name}` : 'Please log in'}
    </div>
  );
}

2. Automatic Route Protection

// Protects routes automatically via middleware
// No need for manual auth checks in components

3. API Route Helpers

// app/api/auth/[...personql]/route.ts
import { createAuthHandler } from '@personql/nextjs';

const handler = createAuthHandler({
  apiKey: process.env.PERSONQL_API_KEY!,
  baseUrl: process.env.PERSONQL_BASE_URL!,
});

export { handler as GET, handler as POST };

4. Protected API Routes

// app/api/profile/route.ts
import { withAuth } from '@personql/nextjs';

export const GET = withAuth(async (request, { user }) => {
  // User is guaranteed to be authenticated
  const profile = await getUserProfile(user.id);
  return Response.json(profile);
});

5. Automatic Analytics

'use client';
import { usePersonQLNext } from '@personql/nextjs';

export default function ProductPage({ product }) {
  const { trackEvent, trackPageView } = usePersonQLNext();

  useEffect(() => {
    // Automatic fingerprinting and page tracking
    trackPageView(`Product: ${product.name}`);
  }, [product]);

  return <div>Product details...</div>;
}

🔧 Configuration

Environment Variables

# Public (client-side)
NEXT_PUBLIC_PERSONQL_API_KEY=your_api_key
NEXT_PUBLIC_PERSONQL_BASE_URL=https://gateway.personql.com

# Private (server-side)
PERSONQL_API_KEY=your_server_api_key
PERSONQL_BASE_URL=https://gateway.personql.com

Advanced Configuration

<PersonQLProvider
  apiKey={process.env.NEXT_PUBLIC_PERSONQL_API_KEY!}
  baseUrl={process.env.NEXT_PUBLIC_PERSONQL_BASE_URL!}
  config={{
    cdp: {
      enabled: true,
      database: 'nextjs_analytics',
      autoTracking: true,
      debug: process.env.NODE_ENV === 'development',
    },
    session: {
      cookieName: 'personql_session',
      maxAge: 60 * 60 * 24, // 24 hours
      secure: process.env.NODE_ENV === 'production',
    },
    auth: {
      redirectTo: '/login',
      afterAuthRedirect: '/dashboard',
      publicRoutes: ['/', '/about', '/contact'],
    },
  }}
>

🆚 Comparison with React SDK

| Feature | React SDK | Next.js SDK | | ----------------- | --------- | ------------- | | Basic Auth | ✅ | ✅ | | SSR Support | ⚠️ Manual | ✅ Automatic | | Route Protection | ❌ Manual | ✅ Middleware | | Server Components | ❌ | ✅ Native | | Token Refresh | ⚠️ Manual | ✅ Automatic | | Session Sync | ❌ | ✅ Unified | | Edge Runtime | ❌ | ✅ Supported |

📖 Migration Guide

From React SDK

  1. Install Next.js SDK

    npm install @personql/nextjs
    npm uninstall @personql/react
  2. Update Imports

    // Before
    import { PersonQLProvider, useAuth } from '@personql/react';
    
    // After
    import { PersonQLProvider, usePersonQLNext } from '@personql/nextjs';
  3. Add Middleware (Optional)

    // middleware.ts - New capability!
    import { createAuthMiddleware } from '@personql/nextjs';
    
    export const middleware = createAuthMiddleware({
      apiKey: process.env.PERSONQL_API_KEY!,
      baseUrl: process.env.PERSONQL_BASE_URL!,
    });
  4. Update Hooks

    // Before - potential hydration issues
    const { isAuthenticated } = useAuth();
    
    // After - SSR-safe
    const { isAuthenticated, isHydrated } = usePersonQLNext();
    
    if (!isHydrated) return <div>Loading...</div>;

🚀 Deployment

Works seamlessly with all Next.js deployment platforms:

  • Vercel - Full support with edge functions
  • Netlify - Complete integration
  • Cloudflare Pages - Optimized for Workers
  • AWS - Lambda and edge support
  • Self-hosted - Docker and traditional hosting

📄 License

MIT License - see LICENSE file for details.


Need help? Check out our examples or contact support.