Securely call LLMs directly from your browser application
Nuabase is designed to let your frontend application call LLMs directly, without routing every request through your own backend API. This reduces latency and server load while keeping your API keys secure.
You need to expose an endpoint (e.g., POST /api/nuabase-token) that returns a token for the currently authenticated user.
Copy
# Gemfile# gem 'nuabase'class NuabaseController < ApplicationController before_action :authenticate_user! def token # Initialize the generator with your secret and the user's ID generator = Nuabase::NuaTokenGenerator.new( signing_key_secret: ENV['NUABASE_SIGNING_KEY_SECRET'], user_id: current_user.id.to_s ) # Generate the token (valid for 3 minutes by default) render json: generator.generate endend
Never expose your NUABASE_SIGNING_KEY_SECRET to the client. It must only be used on your server.
In your frontend application, you initialize the Nua client by providing a fetchToken function. This function is called automatically whenever the SDK needs a fresh token.
Copy
import { Nua } from 'nuabase';import { z } from 'zod';const nua = new Nua({ // The SDK calls this to get a valid token fetchToken: async () => { const response = await fetch('/api/nuabase-token', { method: 'POST', // Include your app's auth headers if needed headers: { 'Content-Type': 'application/json' } }); if (!response.ok) throw new Error('Failed to fetch token'); const data = await response.json(); return data.access_token; }});