@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
andonModalChange
- 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. UsetriggerButton
,showModal
, andonModalChange
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.