JavaScript MediaStream getTrackById() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

The getTrackById() method of MediaStream returns a single MediaStreamTrack that matches an id string, or null if none is found. Learn the MDN commentary ducking pattern, saving track.id from getUserMedia, null handling, and comparison with getTracks()—with five examples and try-it labs.

01

Kind

Instance method

02

Parameter

id string

03

Returns

Track or null

04

Lookup

by track.id

05

Use case

MDN ducking

06

Status

Baseline widely

Introduction

Every MediaStreamTrack has a unique read-only id string. When a stream holds multiple tracks—main audio, commentary, camera, screen share—you often need to target one specific track later. getTrackById(id) does exactly that: pass the id, get the matching track, or null if it is not in this stream.

MDN’s example ducks the primary audio to 50% volume and enables a commentary track—both located by ids you saved earlier. Track ids are randomly generated by the browser, so store them when you first receive the stream rather than hard-coding UUIDs.

💡
Beginner tip

Always check for null before calling methods on the result: const track = stream.getTrackById(id); if (track) track.enabled = true;

Understanding MediaStream.getTrackById()

An instance method that looks up one track in the stream by its MediaStreamTrack.id value.

  • Parametersid: a string identifying the track.
  • Return value — matching MediaStreamTrack, or null if no track has that id.
  • Match rule — compares against MediaStreamTrack.id (strict string match).
  • Scope — only tracks currently in this stream; ids from other streams return null.
  • Pair withgetAudioTracks(), getTracks(), addTrack().
  • Baseline Widely available on MDN (since September 2017).

📝 Syntax

JavaScript
getTrackById(id)

Parameters

id — A string that identifies the track to return (must match MediaStreamTrack.id).

Return value

The MediaStreamTrack whose id matches, or null if no such track exists in the stream.

Typical pattern (MDN idea)

JavaScript
const primaryAudioTrack = stream.getTrackById(
  "69f8520f-d94e-43f0-8a7c-77b1774f3b8f",
);
const commentaryTrack = stream.getTrackById(
  "b5410643-2549-491e-b0f7-f08a4ebe54b8",
);

primaryAudioTrack.applyConstraints({ volume: 0.5 });
commentaryTrack.enabled = true;

MDN notes: ids are browser-generated—save them when you obtain the stream instead of copying example UUIDs.

⚡ Quick Reference

GoalCode / note
Find track by idstream.getTrackById(trackId)
Save id on captureconst id = stream.getAudioTracks()[0].id
Null-safe enableconst t = stream.getTrackById(id); if (t) t.enabled = true
Check existencestream.getTrackById(id) !== null
MDN duckingapplyConstraints({ volume: 0.5 }) on primary track
MDN statusBaseline Widely available (since September 2017)

🔍 At a Glance

Four facts to remember about MediaStream.getTrackById().

Param
id

String

Returns
track|null

One match

Match
track.id

Exact id

Baseline
widely

Since Sep 2017

Examples Gallery

Examples follow MDN MediaStream: getTrackById(). Mic demos use getUserMedia (secure context + permission).

📚 Getting Started

Save a track id, then look it up with getTrackById.

Example 1 — Basic Lookup After getUserMedia

Read track.id, then pass it to getTrackById().

JavaScript
navigator.mediaDevices
  .getUserMedia({ audio: true })
  .then((stream) => {
    const audioId = stream.getAudioTracks()[0].id;
    const found = stream.getTrackById(audioId);
    console.log(found.kind, found.id === audioId);
  });
Try It Yourself

How It Works

The returned track is the same object reference as the original audio track.

Example 2 — Unknown Id Returns null

Pass an id that is not in the stream—MDN: returns null.

JavaScript
const canvas = document.createElement("canvas");
const stream = canvas.captureStream();

const missing = stream.getTrackById("not-a-real-track-id");
console.log(missing);
Try It Yourself

How It Works

Always guard against null before using the track.

📈 MDN Pattern & Comparisons

Commentary ducking and manual find alternatives.

Example 3 — MDN: Duck Primary, Enable Commentary

Look up two tracks by stored ids (MDN pattern with placeholder UUIDs).

JavaScript
// Save real ids when you get the stream — these are MDN placeholders.
const primaryAudioTrack = stream.getTrackById(
  "69f8520f-d94e-43f0-8a7c-77b1774f3b8f",
);
const commentaryTrack = stream.getTrackById(
  "b5410643-2549-491e-b0f7-f08a4ebe54b8",
);

if (primaryAudioTrack) {
  primaryAudioTrack.applyConstraints({ volume: 0.5 });
}
if (commentaryTrack) {
  commentaryTrack.enabled = true;
}
Try It Yourself

How It Works

MDN: use getTrackById when you know track ids from an earlier capture.

Example 4 — getTrackById() vs getTracks().find()

Both locate a track by id; the dedicated method is shorter.

JavaScript
navigator.mediaDevices
  .getUserMedia({ audio: true, video: true })
  .then((stream) => {
    const videoId = stream.getVideoTracks()[0].id;
    const direct = stream.getTrackById(videoId);
    const found = stream.getTracks().find((t) => t.id === videoId);
    console.log(direct === found, direct.kind);
  });
Try It Yourself

How It Works

Prefer getTrackById() for clarity when you have the id string.

Example 5 — Store Track Ids for Later Lookup

Save ids in a map when the stream arrives; look up on button click.

JavaScript
const trackIds = {};

navigator.mediaDevices
  .getUserMedia({ audio: true, video: true })
  .then((stream) => {
    stream.getTracks().forEach((track) => {
      trackIds[track.kind] = track.id;
    });

    const mic = stream.getTrackById(trackIds.audio);
    if (mic) mic.enabled = false;
    console.log(mic && mic.kind);
  });
Try It Yourself

How It Works

Real apps store ids at stream setup time because browser ids are random UUIDs.

🚀 Common Use Cases

  • Switch between main audio and commentary tracks (MDN ducking pattern).
  • Mute or stop one specific track without affecting others in the stream.
  • Re-find a track after UI events when you only stored its id string.
  • Verify a track is still in the stream before applying constraints.
  • WebRTC apps that receive track ids from signaling and attach to local streams.

🔧 How It Works

1

Have a MediaStream

From getUserMedia, addTrack, WebRTC, or captureStream.

Context
2

Pass id string

Call getTrackById(id) where id matches MediaStreamTrack.id.

Lookup
3

Browser searches tracks

Compares id against each track currently in the stream.

Match
4

Track or null

Return the MediaStreamTrack, or null if no match—then act on it safely.

📝 Notes

  • MDN: Baseline Widely available (since September 2017) — no Deprecated / Experimental / Non-standard banner.
  • Null when missing — wrong id, removed track, or id from another stream all return null.
  • Save ids early — browser-generated UUIDs; do not hard-code MDN example ids in production.
  • Null checks — always verify the result before applyConstraints, stop(), or enabled.
  • Related learning: getAudioTracks(), getTracks(), addTrack(), getUserMedia().

Universal Browser Support

MediaStream.getTrackById() is marked Baseline Widely available on MDN (since September 2017). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline · Widely available

MediaStream.getTrackById()

Returns a MediaStreamTrack by id string, or null if not found.

Universal Widely available
Google Chrome Full support · Desktop & Mobile
Full support
Mozilla Firefox Full support · Desktop & Mobile
Full support
Apple Safari Full support · macOS & iOS
Full support
Microsoft Edge Full support · Chromium
Full support
Opera Full support · Modern versions
Full support
Internet Explorer No MediaStream.getTrackById
Not supported
MediaStream.getTrackById() Excellent

Bottom line: Call getTrackById(id) to find one track when you know its MediaStreamTrack.id.

Conclusion

MediaStream.getTrackById(id) finds one track in a stream by its MediaStreamTrack.id string. It returns the matching track or null. Save track ids when you first get a stream—MDN’s commentary example ducks primary audio and enables a second track by id.

Continue with getAudioTracks(), getTracks(), addTrack(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Save track.id when you first receive a stream
  • Check for null before using the returned track
  • Use getTrackById() when you have the id string
  • Pair with track.enabled for on/off toggles
  • Store ids in your app state or signaling payload

❌ Don’t

  • Hard-code MDN example UUIDs in production code
  • Assume getTrackById always returns a track
  • Look up ids from a different MediaStream object
  • Confuse stream.id with track.id
  • Forget secure-context requirements for getUserMedia

Key Takeaways

Knowledge Unlocked

Five things to remember about getTrackById()

Find one track in a stream by its id string.

5
Core concepts
🔗02

Returns

track|null

Result
📦03

Null

no match

Edge
📄04

MDN

ducking

Pattern
🎯05

Baseline

since Sep 2017

Status

❓ Frequently Asked Questions

A MediaStreamTrack object whose id property matches the string you pass. If no track in the stream has that id, it returns null.
No. MDN marks MediaStream.getTrackById() as Baseline Widely available (since September 2017). It is not Deprecated, Experimental, or Non-standard.
One string argument: the track id to look up. MDN documents it as getTrackById(id).
Each MediaStreamTrack has a read-only id string (MediaStreamTrack.id). The browser generates it when the track is created. Save it when you first get the stream if you need to look the track up later.
getTracks() returns every track in the stream as an array. getTrackById(id) returns one track that matches the id, or null if none match.
Duck the main audio track volume to 50% with applyConstraints, then enable a commentary track—both found by stored track IDs with getTrackById().
Did you know?

MDN’s getTrackById() example lowers main audio to 50% with applyConstraints({ volume: 0.5 }) while enabling a commentary track—both found by ids you saved earlier.

List all tracks

Learn getTracks()—every MediaStreamTrack in a stream.

getTracks() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful