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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@chipp/nextjs-chipp

v2.0.13

Published

Easily monetize your generative AI projects with token-based payments in NextJS

Downloads

131

Readme

💳 Chipp.ai - NextJS Package

⚡ Building the pay-per-generation monetization platform for AI applications ⚡

Npm package version npm Documentation Status npm Twitter

Installation

npm i chipp @chipp/nextjs-chipp

NextJS Quickstart

Chipp comes with a specialized NextJS library. Follow the instructions below to integrate.

  1. Sign up for an account on https://app.chipp.ai and create an application to generate your API keys for test and live mode.

  2. In your project directory, install Chipp and the Chipp NextJS library by running npm i chipp @chipp/nextjs-chipp

  3. Add your api key as an environment variable in your app with the name CHIPP_API_KEY

  4. Add the Chipp API to your project by creating a new folder named credits to your /api folder in your NextJS project and create a catch-all route named [...chipp].ts , e.g. pages/api/credits/[...chipp].ts

  5. In the [...chipp].ts file, add the following:

    import { handleCredits } from "@chipp/nextjs-chipp";
    
    export default handleCredits({
      getUserIdFromRequest: async (req, res) => {
        // Return a unique identifier for the user making the request.
        // This value is hashed before it is stored in the Chipp system.
      },
    });

    Whenever a request is made to the Chipp API, we need a way to identify which user is making the request so that we can load their credit balance accordingly. You will need to implement the getUserIdFromRequest function to return a unique identifier from the request, likely using cookies or authorization headers from the request object.

    Here is an example implementation of the getUserIdFromRequest function for an application that uses Auth0 for user authentication:

    import { getSession } from "@auth0/nextjs-auth0";
    import { handleCredits } from "@chipp/nextjs-chipp";
    
    export default handleCredits({
      getUserIdFromRequest: async (req, res) => {
        const session = await getSession(req, res);
        if (!session?.user.sub) {
          res.status(401).json({ error: "Unauthorized" });
          return "";
        }
    
        // This value is hashed before it is stored in the Chipp system.
        return session?.user.sub as string;
      },
    });
  6. Add the <UserCreditsProvider> component as a bottom-level provider in your _app.tsx file.

    import { UserCreditsProvider } from "@chipp/nextjs-chipp/client";
    
    export default function App({ Component, pageProps }) {
      return (
        {/* ...Opening tags for your other providers */}
          <UserCreditsProvider>
            <Component {...pageProps} />
          </UserCreditsProvider>
        {/* ...Closing tags for your other providers */}
      );
    }
  7. In the UI portion of your application, use the useUserCredits React hook to display credit balance of the currently logged-in user.

    import { useUserCredits } from "@chipp/nextjs-chipp/client";
    
    export default function YourComponent() {
      const { userCredits, isLoading: balanceLoading } = useUserCredits();
    
      if (balanceLoading) {
        return <div>Loading...</div>;
      }
    
      // userCredits will be defined once balanceLoading is false
      return <div>Credits: {userCredits}</div>;
    }
  8. When you make a call to your API to generate something for your user that will require deducting a credit (explained in later steps), call refreshBalance after the API call completes to refresh the credit balance of the user.

    import { useUserCredits } from "@chipp/nextjs-chipp/client";
    
    export default function YourOtherComponent() {
      const { refreshBalance } = useUserCredits();
    
      const handleButtonClick = async () => {
        // Your API is responsible for deducting credits
        // from the users balance. We'll explain how to
        // do that in later steps.
        const response = await fetch("/api/generate-thing");
    
        // ...display something from the response to your user
    
        // Update the user's credit balance.
        // Because we use React Context, calling refreshBalance
        // in one part of your app will update the value everywhere.
        refreshBalance();
      };
    
      // ...
    }
  9. In the API endpoint that is responsible for generating something for your user, call deductCredits to deduct credits from the currently logged-in user’s balance. This function will throw an error if the user does not have a sufficient balance, in which case a payment URL will be returned that can be displayed to the user.

    💡 Payment URLs can also be generated on-demand in case you want to allow users to “top up” credits at any time. We will explain how to do this in a later step.


import type { NextApiRequest, NextApiResponse } from "next";
import Chipp from "chipp";

const chipp = new Chipp({
  apiKey: process.env.CHIPP_API_KEY as string,
});

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const session = await getSession(req, res);
  const userId = session?.user?.sub;

  const user = await chipp.getUser({ userId: userId as string });
  if (!user) {
    res.status(400).json({ error: "User not found" });
    return;
  }

  // See if the user has enough credits to send a message
  const userChippBalance = await user.getCredits();
  if (userChippBalance < 1) {
    // Get a payment URL for the user to add more credits
    const paymentURL = await user.getPackagesURL({
      // Return the user to the homepage after they've paid
      // BASE_URL is set in .env to be the URL of the homepage
      returnToUrl: process.env.AUTH0_BASE_URL,
    });
    res.status(200).json({
      content: `You don't have enough credits to send a message. Please add more credits at ${paymentURL}`,
    });
    return;
  }

  // ...generate something for your user

  // Deduct 1 credit from the user
  await user.deductCredits(1);

  res.status(200).json({
    content: // the thing you generated for the user,
  });
}