Example Repository
A complete Next.js implementation showing this integration approach.
For SPAs without a backend, see the simpler Frontend-only approach.
How it works
Installation
@echoxyz/sonar-react since you’ll be making API calls through your backend.
Example storage interfaces
Token storage
You’ll need a way to persist OAuth tokens on the server, keyed by user ID. In production, you should use a database. For demonstration purposes, the example below uses in-memory storage.PKCE verifier storage
During the OAuth flow, you need to store the PKCE code verifier between the initial redirect and the callback. This must be stored server-side and associated with the OAuth state parameter, along with the user ID to verify session consistency.Implementing the OAuth flow
The OAuth flow uses two server actions: one to generate the authorization URL, and one to handle the callback.The
createSonarClient helper used below is defined in the Server actions section.Starting the OAuth flow
When the user clicks “Connect with Sonar”, a server action generates the authorization URL with PKCE parameters:Handling the OAuth callback
After the user authenticates with Echo, they’re redirected to a callback page. This page extracts thecode and state parameters and calls a server action to complete the flow:
Server actions for Sonar API requests
All Sonar API requests go through server actions so that access tokens are never exposed to the browser.Sonar client factory
Create helper functions to instantiate and refresh the Sonar client:Defining server actions
Create acreateSonarServerAction wrapper that handles session authentication and automatic token refresh:
Frontend implementation
With the server actions in place, the client-side components can be implemented as follows:Authentication button
The auth button calls thegetSonarAuthorizationUrl server action and redirects to the returned URL:
Fetching entity state
For the other Sonar API calls, we recommend wrapping these in React hooks. Then these hooks can be called in a very similar way to if you were calling the Sonar API directly via the@echoxyz/sonar-react library.
See the frontend-only guide for an example.