usePlayUrl Hook in Stremio Web: Handling Direct URLs and Magnet Links

The usePlayUrl hook is a custom React hook that centralizes the logic for validating user-provided URLs and magnet links, then launching them in Stremio Web's streaming player.

In the Stremio Web React application (Stremio/stremio-web), the usePlayUrl hook serves as the primary interface for handling direct media inputs. Located at src/common/usePlayUrl.ts, this hook encapsulates validation, toast notifications, and core communication required to transform raw text strings into playable streams.

How usePlayUrl Processes Input Streams

The hook returns an object containing handlePlayUrl, an async function that accepts a string and returns a boolean indicating whether a playable stream was successfully launched. This function discriminates between HTTP URLs and magnet links using protocol-specific validation logic implemented in the source file.

HTTP Stream Handling

When the input matches the internal HTTP_REGEX pattern (detecting http:// or https://), the hook executes a three-step pipeline:

  • User Feedback: Displays a "Loading HTTP stream..." toast notification via the useToast dependency.
  • Stream Registration: Calls core.transport.encodeStream(url) to register the URL with the Stremio core transport layer.
  • Navigation: Updates window.location.hash to #/player/<encoded-url>, triggering the player view route.

If encodeStream throws an exception, the hook catches the error and displays an error toast instead. This logic is implemented in lines 20-35 of src/common/usePlayUrl.ts.

For inputs parseable as magnet URIs (validated via magnet.decode), the hook enforces streaming server prerequisites:

  • Server State Check: Verifies that streamingServer.settings.type === 'Ready' using the useStreamingServer hook. If the server is not ready, it immediately shows an error toast and returns false.
  • Torrent Creation: When the server is ready, invokes createTorrentFromMagnet(trimmed) to initiate the download.
  • Return Value: Returns true to indicate the torrent creation was triggered successfully.

This magnet link pathway appears in lines 47-60 of the source file.

Integration Examples in Stremio Web Components

The usePlayUrl hook is consumed by multiple UI components that accept external media links, demonstrating its utility across different input contexts.

Search Bar Implementation

The SearchBar component (src/components/NavBar/HorizontalNavBar/SearchBar/SearchBar.js) uses the hook to play URLs entered directly into the search field:

import usePlayUrl from 'stremio/common/usePlayUrl';
import { useState } from 'react';

const SearchBar = () => {
  const { handlePlayUrl } = usePlayUrl();
  const [input, setInput] = useState('');

  const onSubmit = async () => {
    const success = await handlePlayUrl(input);
    if (success) {
      setInput('');
    }
  };

  return (
    <input 
      value={input} 
      onChange={(e) => setInput(e.target.value)} 
      onKeyPress={(e) => e.key === 'Enter' && onSubmit()}
    />
  );
};

Clipboard Paste Handling

The NavMenuContent component (src/components/NavBar/HorizontalNavBar/NavMenu/NavMenuContent.js) demonstrates handling clipboard paste events:

import usePlayUrl from 'stremio/common/usePlayUrl';

const NavMenuContent = () => {
  const { handlePlayUrl } = usePlayUrl();

  const onPaste = async (clipboardText: string) => {
    const handled = await handlePlayUrl(clipboardText);
    if (handled) {
      // Close menu or update UI state
    }
  };

  return (
    <div onPaste={(e) => onPaste(e.clipboardData.getData('Text'))}>
      {/* Menu content */}
    </div>
  );
};

Dependencies and Error Handling

The hook relies on two critical Stremio Web utilities:

  • useToast: Provides the toast notification system for "Loading HTTP stream..." and error messages.
  • useStreamingServer: Supplies the streaming server state that the hook checks before attempting to handle magnet links.

All errors generated during stream encoding or torrent creation are caught and surfaced to the user via toast notifications, ensuring the UI never crashes from malformed URLs or unavailable servers.

Summary

  • usePlayUrl is located at src/common/usePlayUrl.ts and exports the handlePlayUrl function for processing external media links.
  • HTTP URLs are encoded via core.transport.encodeStream and routed to #/player/<encoded-url>.
  • Magnet links require the streaming server to be in a Ready state before invoking createTorrentFromMagnet.
  • The hook is consumed by SearchBar and NavMenuContent components to enable direct URL playback from user input or clipboard pastes.
  • Boolean return values allow calling components to react to success or failure states.

Frequently Asked Questions

What does the usePlayUrl hook return?

The hook returns an object containing a single async function, handlePlayUrl(url: string): Promise<boolean>. This function returns true if the input was successfully identified as either an HTTP stream or magnet link and the appropriate playback sequence was initiated, or false if validation failed or the streaming server was unavailable.

The hook uses magnet.decode to verify the input string represents a valid magnet URI. It then checks the streamingServer.settings.type property via the useStreamingServer hook to ensure the value equals 'Ready' before calling createTorrentFromMagnet. If the server is not ready, it displays an error toast and returns false.

What happens when usePlayUrl receives an HTTP URL?

When the input matches the HTTP_REGEX (detecting http:// or https://), the hook displays a loading toast, calls core.transport.encodeStream(url) to register with the Stremio core, and updates the window hash to #/player/<encoded-url>. This hash change triggers the React Router player view to mount and begin streaming.

Where is the usePlayUrl hook used in the Stremio Web interface?

According to the source code analysis, usePlayUrl is imported and utilized in src/components/NavBar/HorizontalNavBar/SearchBar/SearchBar.js for handling search bar inputs, and in src/components/NavBar/HorizontalNavBar/NavMenu/NavMenuContent.js for processing clipboard paste events in the navigation menu.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →