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

@pubflow/nextjs

v0.4.1

Published

Next.js adapter for Pubflow framework with Bridge Payments support

Readme

@pubflow/nextjs

Next.js adapter for the Pubflow framework with Bridge Payments support.

📚 Documentation

Overview

@pubflow/nextjs provides Next.js-specific implementations and utilities for the Pubflow framework, including:

  • Server-side rendering (SSR) support
  • API route handlers for Next.js
  • Bridge Payments - Payment processing with Stripe, PayPal, etc.
  • Authentication - Complete auth flow with Flowless
  • Bridge API - CRUD operations with type safety
  • Next.js-specific storage adapter
  • Integration with Next.js routing (App Router & Pages Router)

Installation

# Install the core package and Next.js adapter
npm install @pubflow/core @pubflow/nextjs

# Optional: Install Zod for schema validation
npm install zod

Schema Validation

Pubflow recommends defining schemas at the application level, not in the adapter. This allows for better reusability and separation of concerns.

// lib/schemas/user.ts
import { z } from 'zod';

// Schema for complete user entity
export const userSchema = z.object({
  id: z.string().uuid().optional(),
  name: z.string().min(2, 'Name must be at least 2 characters'),
  email: z.string().email('Invalid email address'),
  role: z.enum(['user', 'admin'], 'Role must be either user or admin')
});

// Schema for creating a user
export const createUserSchema = userSchema.omit({
  id: true
});

// Schema for updating a user
export const updateUserSchema = userSchema
  .partial()
  .extend({
    id: z.string().uuid()
  });

// TypeScript types inferred from schemas
export type User = z.infer<typeof userSchema>;
export type CreateUser = z.infer<typeof createUserSchema>;
export type UpdateUser = z.infer<typeof updateUserSchema>;

These schemas can then be used with Pubflow's CRUD operations:

import { useBridgeCrud } from '@pubflow/nextjs';
import { userSchema, createUserSchema, updateUserSchema } from '../lib/schemas/user';

function UsersPage() {
  const {
    items: users,
    createItem,
    updateItem,
    deleteItem,
    validationErrors
  } = useBridgeCrud({
    entityConfig: {
      endpoint: 'users'
    },
    schemas: {
      entity: userSchema,
      create: createUserSchema,
      update: updateUserSchema
    }
  });

  // Component implementation...
}

Persistent Cache

Pubflow Next.js adapter supports persistent caching to improve performance and offline experience:

import { PubflowProvider, createPersistentCache } from '@pubflow/nextjs';

function MyApp({ Component, pageProps }) {
  // Create a persistent cache provider
  const persistentCacheProvider = createPersistentCache({
    prefix: 'my_nextjs_app_cache',
    ttl: 24 * 60 * 60 * 1000, // 24 hours
  });

  return (
    <PubflowProvider
      config={{
        baseUrl: 'https://api.example.com',
        bridgeBasePath: '/bridge',
        authBasePath: '/auth'
      }}
      persistentCache={{
        enabled: true,
        provider: persistentCacheProvider
      }}
    >
      <Component {...pageProps} />
    </PubflowProvider>
  );
}

export default MyApp;

For more information, see the persistent cache documentation.

Usage

Provider Setup

// pages/_app.tsx
import { AppProps } from 'next/app';
import { PubflowProvider } from '@pubflow/nextjs';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <PubflowProvider
      config={{
        baseUrl: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8787',
        bridgeBasePath: '/bridge',
        authBasePath: '/auth'
      }}
      loginRedirectPath="/login"
      publicPaths={['/login', '/register', '/forgot-password']}
    >
      <Component {...pageProps} />
    </PubflowProvider>
  );
}

export default MyApp;

Server-Side Authentication

// pages/profile.tsx
import { GetServerSideProps } from 'next';
import { withPubflowSSR, useAuth } from '@pubflow/nextjs';

export const getServerSideProps: GetServerSideProps = withPubflowSSR(
  async (context, api, auth) => {
    // Check if user is authenticated
    const { isValid } = await auth.validateSession();

    if (!isValid) {
      return {
        redirect: {
          destination: '/login',
          permanent: false,
        },
      };
    }

    // Get user data
    const user = await auth.getCurrentUser();

    return {
      props: {
        user,
      },
    };
  }
);

function ProfilePage({ user }) {
  const { logout } = useAuth();

  return (
    <div>
      <h1>Profile</h1>
      <p>Name: {user.name}</p>
      <p>Email: {user.email}</p>
      <button onClick={logout}>Logout</button>
    </div>
  );
}

export default ProfilePage;

API Routes

// pages/api/custom.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { withPubflow } from '@pubflow/nextjs';

export default withPubflow(async (req, res, api) => {
  // Check method
  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    // Make API request
    const response = await api.get('/some/endpoint');

    // Return response
    return res.status(200).json(response.data);
  } catch (error) {
    return res.status(500).json({ error: 'Internal server error' });
  }
});

Protected Routes with useServerAuth

// pages/dashboard.tsx
import { useServerAuth } from '@pubflow/nextjs';

function DashboardPage() {
  // This hook will automatically redirect to login if not authenticated
  const { user, isAuthenticated, isLoading } = useServerAuth({
    loginRedirectPath: '/login',
    allowedTypes: ['admin', 'manager']
  });

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

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

export default DashboardPage;

Bridge Payments

The Next.js adapter includes full support for Bridge Payments, allowing you to process payments with multiple providers.

Basic Usage

import { BridgePaymentClient } from '@pubflow/nextjs';

// Initialize the client
const paymentClient = new BridgePaymentClient({
  baseUrl: process.env.NEXT_PUBLIC_BRIDGE_URL || 'http://localhost:8787',
  basePath: '/payments'
});

// Create a payment intent
const intent = await paymentClient.createPaymentIntent({
  total_cents: 2000, // $20.00
  currency: 'USD',
  description: 'Premium Plan Subscription',
  provider_id: 'stripe'
});

Server-Side Payment Processing

// app/api/create-payment/route.ts
import { BridgePaymentClient } from '@pubflow/nextjs';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  const { amount, description } = await request.json();

  const paymentClient = new BridgePaymentClient({
    baseUrl: process.env.BRIDGE_URL!
  });

  try {
    const intent = await paymentClient.createPaymentIntent({
      total_cents: amount,
      currency: 'USD',
      description,
      provider_id: 'stripe'
    });

    return NextResponse.json({ intent });
  } catch (error) {
    return NextResponse.json(
      { error: 'Payment creation failed' },
      { status: 500 }
    );
  }
}

Client-Side Integration

'use client';

import { BridgePaymentClient } from '@pubflow/nextjs';
import { useState } from 'react';

export default function CheckoutPage() {
  const [loading, setLoading] = useState(false);

  const handlePayment = async () => {
    setLoading(true);

    const client = new BridgePaymentClient({
      baseUrl: process.env.NEXT_PUBLIC_BRIDGE_URL!
    });

    try {
      const intent = await client.createPaymentIntent({
        total_cents: 5000,
        currency: 'USD',
        description: 'Product Purchase',
        provider_id: 'stripe'
      });

      // Redirect to payment or handle client secret
      console.log('Payment Intent:', intent);
    } catch (error) {
      console.error('Payment failed:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <button onClick={handlePayment} disabled={loading}>
      {loading ? 'Processing...' : 'Pay Now'}
    </button>
  );
}

Available Features

  • Payment Intents - Create and manage payment intents
  • Payment Methods - Store and manage customer payment methods
  • Subscriptions - Create and manage recurring subscriptions
  • Customers - Manage customer profiles
  • Addresses - Store billing and shipping addresses
  • Organizations - Multi-tenant payment processing
  • Multiple Providers - Stripe, PayPal, Authorize.net support

For complete Bridge Payments documentation, visit https://bridgepayments.dev/

License

AGPL-3.0-or-later