Blog
Explainer· 3 min read

Sign in with ChatGPT in Express (Node.js): a complete example

Add a "Continue with ChatGPT" button to an Express app. Working code for the OAuth 2.0 + PKCE redirect, the token exchange with client_secret_basic, and ID token verification with jose.

This post shows the whole Sign in with ChatGPT flow in an Express app: two routes, about 70 lines. It follows OpenAI's website integration docs. For the concepts (scopes, tokens, errors), see our developer guide.

Who can use this: the website flow is a limited trial for selected partners. You need an OpenAI client ID (oaiapp_…) and a registered callback URL for each environment. If you don't have one yet, join through OpenAI's interest form. Open-source and local apps don't need approval: see Sign in with ChatGPT in a Python CLI.

What you need

OPENAI_CLIENT_ID=oaiapp_...
OPENAI_CLIENT_SECRET=...
OPENAI_REDIRECT_URI=https://example.com/auth/chatgpt/callback
COOKIE_SECRET=any-long-random-string

The code

// server.mjs
import express from "express";
import cookieParser from "cookie-parser";
import { createHash, randomBytes } from "node:crypto";
import { createRemoteJWKSet, jwtVerify } from "jose";

const ISSUER = "https://auth.openai.com";
const AUTHORIZE = `${ISSUER}/api/accounts/authorize`;
const TOKEN = `${ISSUER}/api/accounts/oauth/token`;
const JWKS = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks.json`));
const { OPENAI_CLIENT_ID, OPENAI_CLIENT_SECRET, OPENAI_REDIRECT_URI, COOKIE_SECRET } = process.env;

const random = () => randomBytes(32).toString("base64url");
const app = express();
app.use(cookieParser(COOKIE_SECRET));

// 1. Start sign-in: fresh state, nonce and PKCE verifier for every attempt.
app.get("/auth/chatgpt", (req, res) => {
  const state = random();
  const nonce = random();
  const verifier = random();
  res.cookie("siwc_tx", JSON.stringify({ state, nonce, verifier }), {
    signed: true,
    httpOnly: true,
    secure: true,
    sameSite: "lax",
    maxAge: 10 * 60 * 1000,
    path: "/auth/chatgpt",
  });

  const url = new URL(AUTHORIZE);
  url.search = new URLSearchParams({
    response_type: "code",
    client_id: OPENAI_CLIENT_ID,
    redirect_uri: OPENAI_REDIRECT_URI, // must match the registered URL exactly
    scope: "openid profile email",
    state,
    nonce,
    code_challenge: createHash("sha256").update(verifier).digest("base64url"),
    code_challenge_method: "S256",
  }).toString();
  res.redirect(url.toString());
});

// 2. Callback: check state, exchange the code, verify the ID token.
app.get("/auth/chatgpt/callback", async (req, res) => {
  const tx = req.signedCookies.siwc_tx;
  res.clearCookie("siwc_tx", { path: "/auth/chatgpt" }); // one use only

  if (!tx || req.query.error || !req.query.code) return res.status(400).send("Sign-in failed");
  const { state, nonce, verifier } = JSON.parse(tx);
  if (req.query.state !== state) return res.status(400).send("Invalid state");

  // Confidential clients use client_secret_basic: id and secret in the Authorization header, never the body.
  const basic = Buffer.from(
    `${encodeURIComponent(OPENAI_CLIENT_ID)}:${encodeURIComponent(OPENAI_CLIENT_SECRET)}`,
  ).toString("base64");
  const tokenRes = await fetch(TOKEN, {
    method: "POST",
    headers: { "content-type": "application/x-www-form-urlencoded", authorization: `Basic ${basic}` },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      code: String(req.query.code),
      redirect_uri: OPENAI_REDIRECT_URI,
      client_id: OPENAI_CLIENT_ID,
      code_verifier: verifier,
    }),
  });
  if (!tokenRes.ok) {
    console.error("token exchange failed", tokenRes.status, tokenRes.headers.get("x-request-id"));
    return res.status(502).send("Sign-in failed");
  }
  const { id_token } = await tokenRes.json();

  let claims;
  try {
    ({ payload: claims } = await jwtVerify(id_token, JWKS, { issuer: ISSUER, audience: OPENAI_CLIENT_ID }));
  } catch {
    return res.status(400).send("Invalid ID token");
  }
  if (claims.nonce !== nonce) return res.status(400).send("Invalid nonce");

  // claims.sub is the stable ChatGPT account ID. Look users up by sub first;
  // link to an existing account by email only when claims.email_verified === true.
  const user = await findOrCreateUser({
    sub: claims.sub,
    email: claims.email,
    emailVerified: claims.email_verified === true,
    name: claims.name,
  });
  await startSession(res, user); // your own HttpOnly, Secure, SameSite=Lax session cookie
  res.redirect("/");
});

app.listen(3000);

findOrCreateUser and startSession are your app's own functions. Keep OpenAI's tokens on the server: never send them to browser JavaScript.

The button

Link your button to /auth/chatgpt, label it Continue with ChatGPT, and add the data-oai-siwc-button attribute so OpenAI can verify your integration:

<a href="/auth/chatgpt" data-oai-siwc-button>Continue with ChatGPT</a>

Common mistakes

When something fails, log the x-request-id (or openai-request-id) response header. OpenAI asks for it when you report a problem.

Next steps