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

@lightski/react

v2.1.1

Published

React SDK for Lightski

Downloads

102

Readme

React SDK

A tool for embedding Lightski into your application with React. This library contains a React component which will allow you to add an iframe to your application containing Lightski, allowing you to display custom analytics to your users.

Getting Started

Installation

You can install this package with npm:

npm install --save @lightski/react

Implementation

Server Setup

Set up an API endpoint on your server that authenticates your user and signs a JWT. Use any JWT library you like appropriate for your server. A Node.js example with a Koa server is shown here:

import { SignJWT } from "jose";

const CLIENT_ID = "YOUR_LIGHTSKI_CLIENT_ID_HERE";

router.post("/api/my-jwt-endpoint", async (ctx) => {
  // Authenticate your user however you do so here
  // const user = ...

  // Make sure this is stored in your ENV variables and not exposed publicly!
  const clientSecret = process.env.LIGHTSKI_CLIENT_SECRET;

  const userJwt = await new SignJWT({
    iss: CLIENT_ID,
    userId: user.id,
  })
    .setProtectedHeader({ alg: "HS256" })
    .sign(new TextEncoder().encode(clientSecret));

  ctx.body = { userJwt };
});

Or in Python (Flask server) using PyJWT:

import jwt
import os

# Retrieve clientSecret from environment variable
clientSecret = os.getenv('YOUR_LIGHTSKI_CLIENT_SECRET_HERE')
# You can set the CLIENT_ID as needed
CLIENT_ID = 'YOUR_LIGHTSKI_CLIENT_ID_HERE'

@app.route('/api/my-jwt-endpoint', methods=['POST'])
def generate_jwt():
    # Authenticate your user however you do so here
    # user = ...

    # Create the JWT payload
    payload = {
        'iss': CLIENT_ID,
        'userId': user['id']
    }

    # Generate the JWT using the HS256 algorithm
    userJwt = jwt.encode(payload, clientSecret, algorithm='HS256')

    return jsonify({'userJwt': userJwt})

Pass the JWT to your client for the next step.

Client React Setup

On your client, fetch the signed JWT from your server and pass it to LightskiEmbedder:

import { LightskiEmbedder } from "@lightski/react";
import React, { useEffect, useState } from "react";

const CLIENT_ID = "YOUR_LIGHTSKI_CLIENT_ID_HERE";
const EMBED_TOKEN = "YOUR_DESIRED_EMBED_TOKEN_HERE";

export default function AnalyticsPage() {
  const [userJwt, setUserJwt] = useState(null);

  async function fetchJwt() {
    // Use whatever fetch library you're used to
    const response = await fetch("/api/my-jwt-endpoint-here", { method: "POST" });
    const responseJson = await response.json();
    setUserJwt(responseJson.userJwt);
  }

  useEffect(() => {
    fetchJwt();
  }, []);

  return (
    <div className="h-full">
      {!userJwt && <div>Loading...</div>}
      {userJwt && (
        <LightskiEmbedder
          location="inline"
          className="h-full w-full"
          clientId={CLIENT_ID}
          userJwt={userJwt}
          embedToken={EMBED_TOKEN}
          // For your security, make sure this is false in production!
          devMode={false}
          // For client-side debug logs, set this to true
          debug={false}
        />
      )}
    </div>
  );
}

Usage

Embed Location

The LightskiEmbedder component can be used in one of two ways: "inline" or "modal". "inline" is the default.

Specify location="modal" to display Lightski inside a modal. When this is the case, you can either:

  • control the modal yourself using showModal and onModalChange
  • use it in an uncontrolled fashion by passing triggerButton, which will be rendered in-line and open the modal.

API

clientId

Your Lightski Client ID, obtained here.

userJwt

The JWT you created in your server that authenticates your user to Lightski.

embedToken

The embed token of the Embed you want to display. This can be obtained from the Embed page in Lightski.

location (optional)

  • "inline" if you want to display the embed inline (default).
  • "modal" if you want to display the embed in a modal. Use triggerButton, showModal, and onModalChange to trigger and/or control the modal state.

key (optional)

Used to uniquely identify this Embed in the DOM. React requires this if you render multiple LightskiEmbedder instances in an array.

className (optional)

Passthrough classname of the iframe element.

style (optional)

CSS styles of the iframe element. React recommends using className instead, due to performance implications.

devMode (optional)

Pass true in development to skip origin security checks and to print error messages to the console.

debug (optional)

Pass true to print additional debugging information to the console.

onError (optional)

Callback function called when an error occurs.

onLaunched (optional)

Callback function called when the Lightski embed is launched.