App
Next.js
Add the SDK
- 1
Install @spur.us/monocle-nextjs
Run the following command to install the SDK:
terminalnpm install @spur.us/monocle-nextjs - 2
Set your Monocle API keys
Add these keys to your
.envor create the file if it doesn't exist..envNEXT_PUBLIC_MONOCLE_PUBLISHABLE_KEY=<MONOCLE PUBLISHABLE KEY>MONOCLE_SECRET_KEY=<your-secret-key> - 3
Add MonocleProvider to your app
Wrap your app with the
MonocleProvidercomponent.tsximport type { Metadata } from "next";import { MonocleProvider } from "@spur.us/monocle-nextjs";import { Geist, Geist_Mono } from "next/font/google";import "./globals.css";const geistSans = Geist({variable: "--font-geist-sans",subsets: ["latin"],});const geistMono = Geist_Mono({variable: "--font-geist-mono",subsets: ["latin"],});export const metadata: Metadata = {title: "Monocle Next.js Example",description: "Generate by create next app",};export default function RootLayout({children,}: Readonly<{children: React.ReactNode;}>) {return (<html lang="en"><body className={`${geistSans.variable} ${geistMono.variable} antialiased`}><MonocleProvider>{children}</MonocleProvider></body></html>);}
Session-Level Analysis (Optional)
- 4
Add useMonocle to your form component
Use the
useMonoclehook to get the assessment and pass it with your form submission. Monocle appends the encrypted assessment when you include it in the request body.tsx"use client";import { useMonocle } from "@spur.us/monocle-nextjs";import { useState } from "react";export default function Form() {const { assessment, isLoading } = useMonocle();const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {e.preventDefault();const formData = new FormData(e.target as HTMLFormElement);await fetch("/api/submit", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({email: formData.get("email"),password: formData.get("password"),monocle: assessment,}),});};if (isLoading) return <div>Loading...</div>;return (<form onSubmit={handleSubmit}><input type="email" name="email" /><input type="password" name="password" /><button type="submit">Submit</button></form>);} - 5
Add your secret key
Set your Monocle secret key as an environment variable for server-side decryption.
.envNEXT_PUBLIC_MONOCLE_PUBLISHABLE_KEY=<MONOCLE PUBLISHABLE KEY>MONOCLE_SECRET_KEY=<your-secret-key> - 6
Decrypt the assessment
Use
monocleClientfrom@spur.us/monocle-nextjs/serverto decrypt the assessment in your API route.typescriptimport { NextRequest, NextResponse } from "next/server";import { monocleClient } from "@spur.us/monocle-nextjs/server";export async function POST(request: NextRequest) {const body = await request.json();try {const monocle = await monocleClient();const decryptedAssessment = await monocle.decryptAssessment(body.monocle);// Handle decrypted assessment} catch (error) {// Handle error}}
Related
- Monocle Assessment — Understand the decrypted assessment payload
- Assessment Decryption — Decryption API and backend decryption options