# JavaScript: React, Next.js, Vite and Node
Source: https://sovaria.in/docs/javascript-frameworks

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.

## React: session state

useSession.ts:
```ts
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

RequireAuth.tsx:
```ts
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 />
}
```

> **Warning:** Hiding a page protects nothing by itself — the data is protected by your access policies and row-level security on the server ([How access is decided](https://sovaria.in/docs/access-model)). Routes only decide what to show.

## 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](https://sovaria.in/docs/javascript-setup).

## 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](https://sovaria.in/docs/connect-your-app).

app/api/orders/route.ts:
```ts
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](https://sovaria.in/docs/sessions-and-tokens)). Keep one service-role client for your own work.

server.js:
```js
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 })
  }
})
```
