Developer Docs
sgID v2
Comment on page

TypeScript / JavaScript

Integrating with TypeScript and JavaScript Node.js applications

Installing the TypeScript / JavaScript Node.js SDK

npm i @opengovsg/sgid-client

Framework Guides

If you are using one of the TypeScript / JavaScript frameworks below, you may refer to our in-depth guides:
If not, read on for a framework-agnostic Quick Start in the next section.

Quick start

The sgID SDK is meant to be used within server-side code (i.e. your backend code). As such, the following steps contain code snippets that should only be run on the server. If you would like to view more details about how your frontend should interact with your backend, please view one of our Framework Guides.

Step 1: Initialize the SDK

If you have not already obtained your client credentials via registration, please register your client before proceeding.
const sgidClient = new SgidClient({
clientId: String(process.env.SGID_CLIENT_ID),
clientSecret: String(process.env.SGID_CLIENT_SECRET),
privateKey: String(process.env.SGID_PRIVATE_KEY),
redirectUri: String(process.env.SGID_REDIRECT_URI)
Load your sgID credentials in a secure way using environment variables instead of hard-coding them into your app.

Step 2: Generate a code verifier and challenge pair

You should generate a new pair for each authorization request, and store the code verifier somewhere you can retrieve it when your user returns from logging into sgID (e.g. in the user's session).
const { codeChallenge, codeVerifier } = generatePkcePair();

Step 3: Generate the authorization URL

const { url, nonce } = sgidClient.authorizationUrl({
You should store the nonce somewhere you can retrieve it when your user returns from logging into sgID, likely in the same place that you store the code verifier.

Step 4: Receive the redirect

After your user logs in to sgID, they will be redirected to your redirect URI with the authorization code (code) in the query parameters. At this point, you should retrieve the code verifier and nonce from where they were stored in steps 2 and 3 respectively.
const { accessToken, sub } = await sgidClient.callback({
The sub is an end-user's unique sgID identifier, and is used together with the access token in the next step to retrieve the user's data. Feel free to use the sub to identify your user in your application as necessary.

Step 5: Retrieve the data

The final step is to retrieve the data, which will contain the scopes requested in step 3.
const userinfo = await sgidClient.userinfo({

API reference

For more detailed documentation for each function, visit our API reference.