Instructions for installing Archetype's Javascript / typescript SDK with Next.js projects.

What is Archetype

Archetype is a powerful, reliable platform for API companies by managing the entire billing and authorization infrastructure for APIs. We have a ton of SDKs for different backends and a ton of component libraries for companies to use.

Requirements

This project requires NodeJS (version 8 or later) and NPM.

$ npm -v && node -v
6.4.1
v8.16.0

ArcheType Next.js middleware can be installed and used with Next.js projects that support (version 9 or later).

Table of contents

Installation Guide

Step 1: Install and Import Archetype

NPM:

$ npm install archetype-nextjs --save

Yarn

$ yarn add archetype-nextjs

Step 2: Add this snippet to a new file where you initialize your ArcheType middleware instance (for example: lib/archetype.ts)

// lib/archetype.ts
import ArcheTypeMiddleware from "archetype-nextjs";

export const archetype = new ArcheTypeMiddleware({
  app_id: process.env.APP_ID as string,
  secret_key: process.env.SECRET_KEY as string,
  handle_auth: false, // toggle this if you want to handle authentication via archeType
});

What this does is it adds the Archetype middleware to automatically authorize your users and log events.

You can further customize and configure parameters in your SDK like setting whether you want to use our auth system.

Step 3: Wrap each API handler individually with the middleware method:

// pages/api/hello.ts
import { archetype } from 'lib/archetype';

async function handler(req, res) {
  res.status(200).json({ data: 'Hello world!' });
}

export default archetype.withMiddleware(handler);

Step 4: Use middleware functions inside you API route

// pages/api/products.ts
import { archetype } from 'lib/archetype';
import { getProducts } from 'archetype-nextjs';

async function handler(req, res) {
  const products = await getProducts();
  res.status(200).json({ data: products });
}

export default archetype.withMiddleware(handler);

Middleware functions

Register your users

Archetype provides a way to register new users and new API Keys via our SDK.

import { registerUser} from 'archetype-nextjs';

async function handler(req, res) {
 registerUser("CUSTOM_UID", "Archetype Team", "[email protected]").then(
   newUser => {
    res.send(newUser)
   } 
  )
}

export default archetype.withMiddleware(handler);

You can pass a custom uid which is a unique identifier for each user and optionally add details like their emails to register a new user. You'll soon be able to add custom attributes and flags for each user. This will automatically create an API key.

Below is a sample response after generating a new user

{
    "apikey": "USERS_APIKEY",
    "attrs": {},
    "custom_uid": "CUSTOM_UID",
    "description": null,
    "email": "[email protected]",
    "first_seen": 1647895155.932904,
    "is_new": true,
    "is_trial": false,
    "last_seen": 1647895155.932909,
    "name": "Archetype Team",
    "quota": 0,
    "status": "not_subscribed",
    "subscription_date": null,
    "subscription_id": null,
    "tier_id": null,
    "trial_end": null
}

The API Key will not be tied to a specific plan unless the user subscribes.

Retrieve User

When the user is logged in and authorized whether via a session based token or however you think about auth, you can actually pass their custom_uid unique identifier to get their details like API keys, quota, usage and more. More details can be found in the Users page.

Below is an example of adding an endpoint that returns user details

import { getUser} from 'archetype-nextjs';

async function handler(req, res) {
 getUser("CUSTOM_UID").then(
   user => {
    res.send(user)
   } 
  )
}

export default archetype.withMiddleware(handler);

This returns a user JSON object

{
    "apikey": "USERS_API_KEY",
    "app_id": "YOUR_APP_ID",
    "attrs": {},
    "custom_uid": "CUSTOM_UID",
    "email": "[email protected]",
    "first_seen": 1647895155.932904,
    "is_new": true,
    "is_trial": false,
    "last_seen": 1647895155.932909,
    "last_updated": 1647895155.932909,
    "quota": 0,
    "renewal_number": 0,
    "start_time": 1647839226,
    "status": "not_subscribed",
    "tier_id": null,
}

Retrieve Available Products

This function returns all the products that you currently and publicly offer to your users. Pulling this list is how you can dynamically render prices.

import { getProducts} from 'archetype-nextjs';

async function handler(req, res) {
 getProducts().then(
   products=> {
    res.send(products)
   } 
  )
}

export default archetype.withMiddleware(handler);

This returns a JSON object that is a list of products.

[
  {
    app_id: 'YOUR_APP_ID',
    currency: 'usd',
    description: 'Basic tier',
    endpoints: [],
    has_full_access: true,
    has_quota: true,
    has_trial: true,
    is_active: true,
    is_free: false,
    is_new: true,
    name: 'Basic',
    period: 'month',
    price: 124,
    quota: 1000,
    tier_id: 'YOUR_TIER_ID',
    trial_length: 7,
    trial_time_frame: 'days'
  }
]

We have a ton of SDKs for frontend libraries that make this process very straightforward but this is helpful if you want to keep as much control in your services as possible. The only caveat is that pulling this data and piping it from your backend services to frontend might create a less optimal pricing page experience.

Generate Checkout Sessions.

Once you get a product, you can pass the tier_id provided in the getproducts function and the user's custom_uid to generate a checkout session url.

What this does is create an ephemeral link to stripe that allows the user to enter their credit card details to purchase a subscription. This handles both creating and updating a checkout session.

The function returns a URL which you can then use to redirect a user to. In your API Settings Page on the Archetype side, you can set a return and redirect url after they've completed (or cancelled) the checkout process.

import { createCheckoutSession} from 'archetype-nextjs';

async function handler(req, res) {
 createCheckoutSession("CUSTOM_UID", "tier_id").then(
    checkoutSessionURL => {
     res.send({
       "url": checkoutSessionURL
      })
  })
}

export default archetype.withMiddleware(handler);

Cancel Products

We lastly provide an easy functionality for you to allow a user to cancel their subscription without any headache on your end.

import { cancelSubscription} from 'archetype-nextjs';

async function handler(req, res) {
 cancelSubscription("CUSTOM_UID").then(
    response => {
     res.send(response)
  })
}

export default archetype.withMiddleware(handler);

Tracking without Middleware

If you want to track individual endpoints, you can simply add a track function to the call that'll asynchronously log the call without any further input.

You can optionally supply the user's API Key or their Custom uid that you provided to track events based on users.

import { track} from 'archetype-nextjs';

async function handler(req, res) {
 track("CUSTOM_UID", req,res)
 res.send('Hello World!')
}

export default handler;

Notice that we are not wrapping the Next.js API route handler in the withMiddleware method here.

API

ArcheTypeMiddleware

class ArcheTypeMiddleware {
  constructor(options: InitOptions) {}
  withMiddleware: (handler: NextApiHandler) => NextApiHandler;
}

type InitOptions = {
  app_id: string;
  secret_key: string;
  handle_auth?: boolean;
};

registerUser

const registerUser: (uid: string, name: string, email: string) => Promise<User>;

getUser

const getUser: (uuid: string) => Promise<User>;

getProducts

const getProducts: () => Promise<Product[]>;

createCheckoutSession

const createCheckoutSession: (uid: string, productId: string) => Promise<string>;

cancelSubscription

const cancelSubscription: (uuid: string) => Promise<void>;

Did this page help you?