Docs

JavaScript: React, Next.js, Vite and Node

Use the SDK in React (session state and protected routes), Next.js (client components, route handlers and server rendering as the user), Vite, and Node.js servers such as Express.

Updated Oct 17, 2026

React: session state

import { useEffect, useState } from 'react'
import { sovaria } from './sovaria'

export function useSession() {
  const [session, setSession] = useState(() => sovaria.auth.getSession())
  useEffect(() => sovaria.auth.onAuthStateChange((_event, s) => setSession(s)), [])
  return session
}

Protected routes

import { Navigate } from 'react-router-dom'
import { useSession } from './useSession'

export function RequireAuth({ children }: { children: JSX.Element }) {
  const session = useSession()
  return session ? children : <Navigate to="/login" replace />
}

Vite

Put VITE_SOVARIA_URL and VITE_SOVARIA_ANON_KEY in .env (never a server key — anything prefixed VITE_ ends up in the bundle) and create the client once, as in JavaScript: install and configure.

Next.js

  • Client components: create the client with NEXT_PUBLIC_SOVARIA_URL and NEXT_PUBLIC_SOVARIA_ANON_KEY; sessions persist in the browser.
  • Route handlers acting as the user: send the user's access token from the browser as an Authorization header (sovaria.auth.getSession()?.access_token) and create a client per request with setAccessToken, so their access policies and row security apply.
  • Server work as your app: use the service role key from a server-only variable (no NEXT_PUBLIC_ prefix) — set up in Connect your app.
import { createClient } from '@sovaria/sdk'

export async function GET(req: Request) {
  const token = req.headers.get('authorization')?.replace(/^Bearer /, '')
  if (!token) return new Response('Sign in', { status: 401 })

  const sovaria = createClient(process.env.NEXT_PUBLIC_SOVARIA_URL!, process.env.NEXT_PUBLIC_SOVARIA_ANON_KEY!, { persistSession: false })
    .setAccessToken(token)
  const { rows } = await sovaria.data.sql('select id, total from orders order by id desc limit 20')   // row security applies
  return Response.json(rows)
}

Node.js servers (Express)

Forward the caller's token so Sovaria's policies decide, or verify it yourself against the project's JWKS (Sessions and tokens). Keep one service-role client for your own work.

import express from 'express'
import { createClient } from '@sovaria/sdk'

const app = express()
const asUser = (token) => createClient(process.env.SOVARIA_URL, process.env.SOVARIA_ANON_KEY, { persistSession: false }).setAccessToken(token)

app.get('/api/me/orders', async (req, res) => {
  const token = req.get('authorization')?.replace(/^Bearer /, '')
  if (!token) return res.sendStatus(401)
  try {
    const { rows } = await asUser(token).data.sql('select id, total from orders')
    res.json(rows)
  } catch (err) {
    res.status(err.statusCode || 500).json({ error: err.message })
  }
})
Something unclear or missing on this page?Tell us