6 min read

How to Monitor Session Duration in Google Analytics 4

Session duration tells you how long users are actually engaged on your site—but GA4 doesn't surface it as a default metric. Instead, GA4 measures engagement time and categorizes sessions as engaged or not. If you're trying to diagnose where users drop off or measure content performance, you need to know how to find and track session duration data.

Finding Session Duration Data in GA4 Reports

GA4 doesn't call it 'session duration'—it uses engagement metrics. Here's where to look.

Navigate to the Engagement report

In GA4, go to Reports > Engagement > Overview. This shows total engaged sessions and engagement rate. But to see the actual duration breakdown, you need to create a custom report.

Build a custom report with session metrics

Click Create custom report and add Session duration (under Dimensions: Session) alongside Engagement duration and Bounce rate. This gives you the full picture of how long sessions last and which ones resulted in meaningful interaction.

javascript
// Retrieve session metrics via the Google Analytics Data API
const response = await google.analyticsdata('v1beta').properties.runReport({
  property: 'properties/YOUR_PROPERTY_ID',
  requestBody: {
    dateRanges: [{
      startDate: '2024-01-01',
      endDate: 'today'
    }],
    dimensions: [{ name: 'sessionDefaultChannelGroup' }],
    metrics: [
      { name: 'engagementDuration' },
      { name: 'sessions' },
      { name: 'engagedSessions' }
    ]
  }
});
Query GA4 Data API to retrieve session duration metrics programmatically

Filter by user segments or traffic source

Once you have the report, apply filters in Filters to isolate specific user cohorts (e.g., new vs. returning, organic vs. paid). This reveals which segments spend the most time on your site.

Implement Custom Session Duration Tracking

If you want to measure session duration independently or track it as a custom event, use gtag.js to send session data to GA4.

Initialize gtag.js with session tracking enabled

Add the GA4 tag to your website and ensure session tracking is active. GA4 automatically creates a unique session ID and resets it after 30 minutes of inactivity by default.

javascript
<!-- Add GA4 tag to your page -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-XXXXXXXXXX');
</script>
Standard GA4 gtag.js initialization

Send a custom event when sessions end

Track the session duration as a custom event. Calculate the duration from the first interaction timestamp to the last interaction, then fire an event with that data.

javascript
// Track session duration at the end of user interaction
let sessionStartTime = Date.now();

window.addEventListener('beforeunload', () => {
  const sessionDuration = Math.round((Date.now() - sessionStartTime) / 1000);
  gtag('event', 'session_end', {
    'session_duration': sessionDuration,
    'engagement_time_msec': sessionDuration * 1000
  });
});
Send custom session duration event to GA4

View session events in the Events report

Go to Reports > Engagement > Events and search for your custom event (e.g., session_end). You'll see the count and can add session_duration as a custom metric to see the average and distribution.

Query Session Duration via the Data API

For automated reporting or deeper analysis, use the Google Analytics Data API to pull session metrics programmatically.

Authenticate with a service account

Create a service account in Google Cloud, download the JSON key, and authenticate your requests. You'll need the OAuth 2.0 access token to make API calls.

javascript
// Authenticate with Google Analytics Data API using service account
const { BetaAnalyticsDataClient } = require('@google-analytics/data');
const analyticsDataClient = new BetaAnalyticsDataClient();

const request = {
  property: `properties/YOUR_PROPERTY_ID`,
  dateRanges: [{
    startDate: '2024-03-01',
    endDate: '2024-03-26'
  }],
  dimensions: [{ name: 'date' }],
  metrics: [{ name: 'engagementDuration' }]
};

const response = await analyticsDataClient.runReport(request);
Authenticate and query GA4 session metrics via the Data API

Parse the API response and calculate insights

The API returns arrays of dimension and metric values. Iterate through the rows to calculate average session duration, percentiles, or other statistics.

javascript
// Parse API response and calculate average session duration
const rows = response.rows;
let totalDuration = 0;

rows.forEach(row => {
  const duration = parseInt(row.metricValues[0].value, 10);
  totalDuration += duration;
});

const avgSessionDuration = Math.round(totalDuration / rows.length);
console.log(`Average session duration: ${avgSessionDuration}ms`);

// Convert to seconds for readability
const avgSeconds = (avgSessionDuration / 1000).toFixed(2);
console.log(`Average session duration: ${avgSeconds} seconds`);
Calculate average session duration from API data

Set up automated reports

Wrap this query in a scheduled function (e.g., Cloud Scheduler, Lambda, or a cron job) to send daily or weekly session duration summaries to your team via email or Slack.

Common Pitfalls

  • GA4 only counts milliseconds of active engagement—if a user leaves the tab open but doesn't interact, the timer stops. This means session duration can be significantly lower than time-on-site.
  • Session duration resets after 30 minutes of inactivity by default. Long sessions may be split into multiple sessions in your reports, inflating your session count.
  • The Data API returns engagement duration in milliseconds, but GA4 reports round to the nearest second. Automated queries will show more precision than the UI.
  • Custom events sent via gtag.js may be delayed by a few seconds. If you measure session duration on page unload, some events might not be recorded if the user closes the browser immediately.

Wrapping Up

Monitoring session duration in GA4 requires looking beyond the default metrics—use engagement reports for quick analysis and the Data API for automation. Track custom session events with gtag.js to measure user engagement the way your business defines it. If you want to track this automatically across tools, Product Analyst can help.

Track these metrics automatically

Product Analyst connects to your stack and surfaces the insights that matter.

Try Product Analyst — Free