API keys
A person makes a key for the brand's own API, for a script of theirs, and the API checks it with Synq on every request: here, the demo's own API.
Built on @synqauth/react over @synqauth/nextjs’s route mount, so it needs a server of yours. In a single-page app, createAccountClient from @synqauth/js makes and revokes them (apiKeys). @synqauth/js in the docs
Loading…
Call the demo API with a key
src/examples/api-keys/Headless.tsx'use client'
import { type NewApiKey, useApiKeys, useAuth, useKeyableApis } from '@synqauth/react'
import { useState } from 'react'
// API keys headless: useKeyableApis lists the brand's APIs that take keys,
// apiKeys.create makes one (the key is in that answer only: show it once),
// useApiKeys lists them without the key, and apiKeys.revoke stops one.
export function ApiKeysHeadless() {
const { data: apis } = useKeyableApis()
const { data: keys, error } = useApiKeys()
const { apiKeys, signIn } = useAuth()
const [made, setMade] = useState<NewApiKey | null>(null)
const [refused, setRefused] = useState<string | null>(null)
if (error) return <p role="alert">{error.message}</p>
if (!apis || !keys) return <p>Loading…</p>
const api = apis[0]
async function make() {
if (!api) return
const scopes = api.scopes.map((scope) => scope.name)
const result = await apiKeys.create({ api: api.identifier, name: 'Headless key', scopes })
setMade(result.data)
setRefused(result.error?.code ?? null)
}
return (
<>
{made && <output aria-label="Your new key">{made.key}</output>}
{refused === 'fresh_sign_in_required' && (
<button type="button" onClick={() => void signIn({ maxAge: 300 })}>
Sign in again to make a key
</button>
)}
<ul aria-label="Your API keys">
{keys.map((key) => (
<li key={key.id}>
{key.name} <code>{key.prefix}…</code> {key.revoked_at ? 'revoked' : ''}{' '}
{!key.revoked_at && (
<button type="button" onClick={() => void apiKeys.revoke(key.id)}>
Revoke {key.name}
</button>
)}
</li>
))}
</ul>
<button type="button" disabled={!api} onClick={() => void make()}>
Make a key for {api?.name ?? 'an API'}
</button>
</>
)
}