Authgear
Start BuildingHomePortalCommunity
  • Authgear Overview
  • Get Started
    • Start Building
    • 5-Minute Guide
    • Single-Page App
      • JavaScript (Web)
      • React
      • Angular
      • Vue
    • Native/Mobile App
      • iOS SDK
      • Android SDK
        • Android Kotlin coroutine support
        • Android OKHttp Interceptor Extension (Optional)
      • Flutter SDK
      • React Native SDK
      • Ionic SDK
      • Xamarin SDK
      • Using Authgear without SDK (Client side)
    • Regular Web App
      • Express
      • Next.js
      • Python Flask App
      • Java Spring Boot
      • ASP.NET Core MVC
      • Laravel
      • PHP
    • Backend/API Integration
      • Validate JWT in your application server
      • Forward Authentication to Authgear Resolver Endpoint
    • AI Coding tools
      • Cursor/Windsurf
  • How-To Guides
    • Authenticate
      • Add Passkeys Login
      • Add WhatsApp OTP Login
      • Add Email Magic Link Login
      • Add Biometric Login
      • Add Anonymous Users
      • Add authentication to any web page
      • Enable Two-Factor Authentication (2FA)
      • How to Use the OAuth 2.0 State Parameter
      • Reauthentication
      • How to Use Social/Enterprise Login Providers Without AuthUI
      • Passwordless Login for Apple App Store Review
      • Setup local development environment for Cookie-based authentication
      • Forgot/Reset Password settings
      • Phone number validation
      • Set Password Expiry
    • Single Sign-on
      • App2App Login
      • Pre-authenticated URLs
      • SSO between Mobile Apps / Websites
      • Force Authgear to Show Login Page
      • Single Sign-On with OIDC
      • Single Sign-On with SAML
        • Use Authgear as SAML Identity Provider for Salesforce
        • Use Authgear as SAML Identity Provider for Dropbox
        • SAML Attribute Mapping
    • Social Login / Enterprise Login Providers
      • Social Login Providers
        • Connect Apps to Apple
        • Connect Apps to Google
        • Connect Apps to Facebook
        • Connect Apps to GitHub
        • Connect Apps to LinkedIn
        • Connect Apps to WeChat
      • Enterprise Login Providers
        • Connect Apps to Azure Active Directory
        • Connect Apps to Microsoft AD FS
        • Connect Apps to Azure AD B2C
      • Force Social/Enterprise Login Providers to Show Login Screen
    • Built-in UI
      • Branding in Auth UI
      • User Settings
      • Privacy Policy & Terms of Service Links
      • Customer Support Link
      • Custom Text
    • Custom UI
      • Authentication Flow API
      • Implement Authentication Flow API using Express
      • Implement Authentication Flow API using PHP
      • Add Custom Login/Signup UI to Native Apps
      • Manually Link OAuth Provider using Account Management API
      • Implement a custom account recovery UI using Authentication Flow API
    • Integrate
      • Add custom fields to a JWT Access Token
      • User Analytics by Google Tag Manager
      • Track User Before and After Signup
      • Custom domain
      • Custom Email Provider
      • Custom SMS Provider
        • Twilio
        • Webhook/Custom Script
    • Monitor
      • Audit Log For Users Activities
      • Audit Log for Admin API and Portal
      • Analytics
    • User Management
      • Account Deletion
      • Import Users using User Import API
      • Export Users using the User Export API
      • Manage Users Roles and Groups
      • How to Handle Password While Creating Accounts for Users
    • User Profiles
      • What is User Profile
      • Access User Profiles
      • Update User Profiles
      • Profile Custom Attributes
      • Update user profile on sign-up using Hooks
    • Events and Hooks
      • Event List
      • Webhooks
      • JavaScript / TypeScript Hooks
      • Only Allow Signups from Inside the Corporate Network using Hooks
    • Mobile Apps
      • Use SDK to make authorized API calls to backend
      • Force authentication on app launch
      • Customize the Login Pop-up / Disable the login alert box
    • Languages and Localization
    • Custom Email and SMS Templates
    • Directly accessing Authgear Endpoint
    • Migration
      • Bulk migration
      • Rolling migration
      • Zero-downtime migration
    • Troubleshoot
      • How to Fix SubtleCrypto: digest() undefined Error in Authgear SDK
      • How to Fix CORS Error
  • Concepts
    • Identity Fundamentals
    • Authgear use cases
    • User, Identity and Authenticator
  • Security
    • Brute-force Protection
    • Bot Protection
    • Non-HTTP scheme redirect URI
    • Password Strength
  • Reference
    • APIs
      • Admin API
        • Authentication and Security
        • API Schema
        • Admin API Examples
        • Using global node IDs
        • Retrieving users using Admin API
        • User Management Examples
          • Search for users
          • Update user's standard attributes
          • Update user's picture
          • Generate OTP code
      • Authentication Flow API
      • OAuth 2.0 and OpenID Connect (OIDC)
        • UserInfo
        • Supported Scopes
      • User Import API
      • User Export API
    • Tokens
      • JWT Access Token
      • Refresh Token
    • Glossary
    • Billing FAQ
    • Rate Limits
      • Account Lockout
  • Client App SDKs
    • Javascript SDK Reference
    • iOS SDK Reference
    • Android SDK Reference
    • Flutter SDK Reference
    • Xamarin SDK Reference
  • Deploy on your Cloud
    • Running locally with Docker
    • Deploy with Helm chart
    • Authenticating HTTP request with Nginx
    • Configurations
      • Environment Variables
      • authgear.yaml
      • authgear.secrets.yaml
    • Reference Architecture Diagrams
      • Google Cloud Reference Architecture
      • Azure Reference Architecture
      • AWS Reference Architecture
      • Throughput Scaling Reference
Powered by GitBook
On this page
  • Prerequisites
  • What We'll Build
  • What is the OAuth 2.0 State Parameter?
  • How to Track a User Who Signs Up from a Particular Source
  • Step 1: Set Up Your App to Use Authgear
  • Step 2: Add State Parameter to Authorization Request
  • Step 3: Read the Value of State After Authorization

Was this helpful?

Edit on GitHub
  1. How-To Guides
  2. Integrate

Track User Before and After Signup

Learn how to track a user that signs up from a particular source or campaign.

PreviousUser Analytics by Google Tag ManagerNextCustom domain

Last updated 1 month ago

Was this helpful?

In this guide, you'll learn how to track users from a particular source before and after they sign up. For example, knowing how many people sign up for your application through a signup link that you have included in a blog post or an email campaign.

Prerequisites

To follow this guide, you need to have the following:

  • A free Authgear account.

  • An application in the Authgear Portal and note down the configuration of the application.

  • A client application that is written in your preferred language or framework.

What We'll Build

For this guide, we'll build a demo Express application that has the following features:

  • Read a source URL parameter defined by you (the developer).

  • Send the value of the source parameter to the Authgear authorization server using the OAuth 2.0 state parameter.

  • Read the value of state returned after user authorization (sign up) and log the value in a database or analytics system like Mixpanel.

What is the OAuth 2.0 State Parameter?

The includes an optional state parameter. The value of the state parameter can be any random string or number defined by a client application (e.g a web or mobile that uses Authgear for user authentication) before the client makes an authorization request. In simple terms, the state parameter is added to the authorization URL as a URL query.

The authorization server (Authgear) will include the same state parameter value when redirecting the user-agent back to the client application. As a result, the client application can retrieve the value of state returned to verify that it is the origin of the authorization request.

We will use the above behavior of the authorization process to track a user before and after they sign up.

How to Track a User Who Signs Up from a Particular Source

The following steps show the steps for building a simple application that is capable of tracking users before and after they sign up.

Step 1: Set Up Your App to Use Authgear

1. Express:

npm install express

2. Axios:

npm install axios

Next, inside the project directory, create a new app.js file then add the following code to the file:

const express = require('express');
const axios = require('axios');

const app = express();
const port = process.env.PORT || 3000;

const config = {
  client: {
    id: "CLIENT_ID",
    secret: "CLIENT_SECRET",
    redirect_url: "REDIRECT_URL"
  },
  auth: {
    tokenHost: "AUTHGEAR_ENDPOINT",
    tokenPath: '/oauth2/token',
    authorizePath: '/oauth2/authorize',
    scope: 'openid offline_access'
  },
};

You can get the correct configuration values (CLIENT_ID, CLIENT_SECRET, REDIRECT_URL, and AUTHGEAR_ENDPOINT) from the Applications section of the Authgear Portal.

Step 2: Add State Parameter to Authorization Request

In this step, we'll implement a /login route in the demo application. This route will support a source query parameter, for example, /login?source=002.

Add the following code to the end of app.js to implement the /login route:

app.get("/login", (req, res) => {

  const url = new URL(`${config.auth.tokenHost}${config.auth.authorizePath}`);
  url.searchParams.set('client_id', config.client.id);
  url.searchParams.set('redirect_uri', config.client.redirect_url);
  url.searchParams.set('response_type', 'code');
  url.searchParams.set('scope', config.auth.scope);

  if (req.query.source != null) {
    url.searchParams.set('state', req.query.source);
  }

  res.redirect(url);
  
});

The above code will check if the source parameter is included in the HTTP request to the /login route. If there is a source parameter, the value of the source will be added to the authorization URL's state parameter.

The following is an example of a login URL that includes the source parameter:

http://localhost:3000/login?source=002

Step 3: Read the Value of State After Authorization

As described earlier, Authgear will return whatever value you put in the state parameter of the authorization URL. In the last step, we will read the value of the source parameter from the /login route and pass it to the state parameter. In this step, we'll read the state parameter that Authgear returns in the redirect URI for the initial value we passed (source).

To do this, we'll add a / route to resolve our redirect URI. Add the following code to the end of app.js to implement the route:

app.get("/", async (req, res) => {

  if (req.query.code != null) {
    const data = {
      client_id: config.client.id,
      client_secret: config.client.secret,
      code: req.query.code,
      grant_type: 'authorization_code',
      response_type: 'code',
      redirect_uri: config.client.redirect_url,
      scope: config.auth.scope
    };

    const sourceFromState = req.query.state;

    try {
      const getToken = await axios.post(`
        ${config.auth.tokenHost}${config.auth.tokenPath}`,
        data,
        {
        headers: { "Content-Type": "application/x-www-form-urlencoded" }
        }
      );

      const accessToken = getToken.data.access_token;
      res.send(`
      <p>Access token: ${accessToken}, ${sourceFromState}</p>
    `);
    } catch (error) {
      res.send("An error occurred! Login could not complete. Error data: " + error);
    }
  }

  else {
    res.send(`
      <div style="max-width: 650px; margin: 16px auto; background-color: #EDEDED; padding: 16px;">
        <p>Hi there!</p>
        <p>This demo app shows you how to add user authentication to your Express app using Authgear</p>
          <p>Checkout <a href="https://docs.authgear.com">docs.authgear.com</a> to learn more about adding Authgear to your apps.</p>
        <a href="/login">Login</a>
      </div>
    `);
  }
});

app.listen(port, () => {
  console.log(`server started on port ${port}!`);
});

The sourceFromState constant holds the value for the state parameter in the redirect URI. You can save this value to a database to track that the user has successfully signed up using the link with the source value in your original campaign link. You may also send this link to an analytic tool like Mixpanel to track the user and source.

To run the demo app, run the following command in the terminal:

node app.js

Then, open http://localhost:3000/login?source=002 on a browser. You can change 002 to any random string that you wish to use for tracking a source or campaign. Also, be sure to add http://localhost:3000 as a redirect URL for your application in the Authgear Portal.

First, create a new project directory and open it. The demo application for this guide is a simple application that use Axios to make HTTP requests. Hence, install both packages using the following commands:

OAuth 2.0 framework
Express