docs
DOCUMENTATION & API REFERENCE

Social URLs,
made simple.

Everything you need to detect, validate, normalize, and render social profile links with Sociurl.

01 / WHAT IT DOES

A small toolkit for profile URLs

Sociurl recognizes social platforms from profile URLs, checks that the host, path, and username follow supported rules, and returns a canonical HTTPS URL. It also includes optional React components and a hook.

Structural validation only. A valid result means the URL matches Sociurl’s supported profile format. It does not check whether the account exists, is active, or belongs to a particular person.
15built-in platforms
4core URL helpers
0core runtime dependencies
Reactoptional integration
02 / GET STARTED

Install and validate a URL

Install Sociurl in your project. Add React only if you use the React entry point.

Terminal
npm install sociurl
Core usage
import { validateSocialUrl } from "sociurl";

const result = validateSocialUrl("instagram.com/ahmad");

if (result.valid) {
  console.log(result.platform);     // "instagram"
  console.log(result.username);     // "ahmad"
  console.log(result.normalizedUrl); // "https://www.instagram.com/ahmad"
} else {
  console.log(result.error.code, result.error.message);
}

Results are a discriminated union. Check result.valid before reading fields: valid results contain a username and normalized URL; invalid results contain an error.

03 / FRAMEWORK-INDEPENDENT

Core API

detectPlatform(url, options?)

Detects a supported platform from the hostname. It can detect a platform even when the profile username is missing. Returns a platform ID or null.

detectPlatform("www.instagram.com/"); // "instagram"
detectPlatform("https://twitter.com/ahmad"); // "x"
detectPlatform("https://instagram.com.fake.com/ahmad"); // null

validateSocialUrl(url, options?)

Validates the host, profile path, username, and protocol. Returns the full valid or invalid result.

validateSocialUrl("https://github.com/ahmad", {
  platform: "instagram", // Optional: require a specific platform
});

validateSocialUrl(url, {
  registry,               // Optional custom PlatformRegistry
  messages,               // Optional error message overrides
});

extractUsername(url, options?)

Returns the validated profile identifier, or null when parsing or validation fails. YouTube channel URLs return the channel ID; Facebook numeric profile URLs return the numeric ID.

extractUsername("https://reddit.com/u/ahmad"); // "ahmad"
extractUsername("https://instagram.com/"); // null

normalizeSocialUrl(url, options?)

Returns the canonical HTTPS profile URL, or null when the URL is not a valid profile.

normalizeSocialUrl("HTTP://instagram.com/ahmad/");
// "https://www.instagram.com/ahmad"

getSupportedPlatforms(options?) and getPlatformInfo(id, options?)

Read all definitions in a registry or retrieve one platform definition. With no registry option, both use the built-in definitions.

const platforms = getSupportedPlatforms();
const instagram = getPlatformInfo("instagram");
04 / CANONICAL OUTPUT

How normalization works

  • Missing protocols become HTTPS. HTTP input is accepted and upgraded to HTTPS.
  • Aliases and canonical domains are normalized, such as Twitter to X.
  • Extra trailing slashes and duplicate empty path segments are removed.
  • Required path prefixes are kept, such as LinkedIn’s /in/ and Reddit’s /user/.
  • Tracking query parameters and fragments are dropped. Query parameters are kept only when the username is stored there.
  • Username casing is preserved. Encoded usernames are safely decoded and re-encoded.
normalizeSocialUrl("https://m.instagram.com/ahmad?hl=en#top");
// "https://www.instagram.com/ahmad"

normalizeSocialUrl("https://reddit.com/u/ahmad");
// "https://www.reddit.com/user/ahmad"
05 / BUILT IN

Supported platforms

Platform matching is based on explicit hostnames, profile patterns, username rules, and reserved paths. Content URLs are not treated as profiles.

PlatformIDProfile format
Instagraminstagram/username
Facebookfacebook/username or /profile.php?id=123
LinkedInlinkedin/in/username
GitHubgithub/username
Xx/username (twitter.com alias)
YouTubeyoutube/@handle, /c/name, /user/name, /channel/ID
TikToktiktok/@username
Pinterestpinterest/username
Redditreddit/user/name or /u/name
Twitchtwitch/username
Mediummedium/@username
Dribbbledribbble/username
Behancebehance/username
Telegramtelegram/username (telegram.me alias)
Threadsthreads/@username (threads.com alias)

Examples of rejected content paths include Instagram posts, YouTube watch pages, and Reddit community pages. Use getSupportedPlatforms() to inspect the installed definitions and icon metadata.

06 / EXTEND THE PLATFORM LIST

Custom platforms and registries

Custom definitions are scoped to a registry instance. Registering one never changes Sociurl’s shared built-ins.

Create and use a custom definition
import { createPlatformRegistry, validateSocialUrl } from "sociurl";
import type { PlatformDefinition } from "sociurl";

const devTo: PlatformDefinition = {
  id: "devto",
  name: "DEV Community",
  domains: ["dev.to"],
  canonicalDomain: "dev.to",
  profilePatterns: [{
    handle: "at", // /@username
    username: { pattern: /^[A-Za-z0-9_]{2,30}$/ },
  }],
  reservedPaths: ["about", "settings"],
};

const registry = createPlatformRegistry({ platforms: [devTo] });
validateSocialUrl("https://dev.to/@ahmad", { registry });

Registry creation options

  • createPlatformRegistry() includes all built-ins by default.
  • includeBuiltIns: false starts with only the custom definitions you pass.
  • platforms registers definitions during creation.

Registry instance methods

register(definition, options?)Adds a definition. Duplicate IDs throw by default; use { overwrite: true } to replace one.
unregister(id)Removes a definition and returns whether one existed.
has(id)Checks whether an ID is registered.
get(id)Returns one definition or null.
getAll()Returns a copy of all registered definitions.
findByHostname(hostname)Finds a definition by exact host and permitted subdomain.

Profile patterns

Path patterns can declare a literal prefix, plain or @ handles, and a canonical prefix. Query patterns declare an exact pathname and the query parameter containing the identifier.

{
  kind: "query",
  pathname: "profile",
  queryParam: "id",
  username: { pattern: /^\d+$/ },
}

Username regular expressions must not use the global or sticky flags. Keep them anchored so they validate the full identifier.

07 / PREDICTABLE FAILURES

Error codes and message overrides

CodeMeaning
INVALID_URLThe input is empty or malformed, contains credentials, uses a non-standard port, or has ambiguous encoding.
UNSUPPORTED_PLATFORMThe hostname is not supported, or does not match the required platform.
MISSING_USERNAMEThe URL has a profile-shaped path but no username.
INVALID_USERNAMEThe username violates the platform’s rules or is reserved.
INVALID_PROFILE_PATHThe URL points to a content page, reserved route, or unsupported path shape.
INVALID_PROTOCOLThe URL uses a scheme other than HTTP or HTTPS.

Each failed validation has an error.code and readable error.message. Override selected messages without changing validation behavior.

validateSocialUrl(url, {
  messages: {
    MISSING_USERNAME: "Add your {platform} handle",
    INVALID_USERNAME: ({ platform, defaultMessage }) =>
      platform ? "That is not a valid " + platform.name + " handle" : defaultMessage,
  },
});

String overrides support the {platform} token. Function overrides receive code, platform, and the original defaultMessage.

Error factory helpers are also exported: createValidationError, invalidUrl, unsupportedPlatform, missingUsername, invalidUsername, invalidProfilePath, and invalidProtocol.

08 / OPTIONAL REACT ENTRY

React integration

Install React and React DOM if you use the React entry point:

npm install react react-dom
import { SocialInput, SocialIcon, SocialLinks, useSocialValidator } from "sociurl/react";

SocialInput

A platform-aware input with controlled or uncontrolled value, validation, accessible labeling, and customizable messages.

<SocialInput
  platform="instagram"
  label="Instagram profile"
  value={url}
  onChange={(value, event) => setUrl(value)}
  onValidationChange={setResult}
  validateOn="change" // or "blur"
  messages={messages}
/>

Pass native input props such as placeholder, disabled, name, and aria-*. The callback receives the new string first and the input event second.

It ships without CSS. Customize the wrapper, label, field, icon, input, and error with the matching *ClassName and *Style props. showIcon, showError, iconSize, iconColor, colorStyle, and renderError control presentation.

SocialIcon

Renders the package’s bundled platform icon data. It returns null when the platform has no icon. Default fill inherits currentColor; colorStyle="brand" opts into the platform brand color, and an explicit color takes precedence.

<SocialIcon platform="instagram" size={28} colorStyle="brand" />
<SocialIcon platform="github" color="#ffffff" decorative />

Props include platform, size, color, colorStyle, label, decorative, and registry.

SocialLinks

Validates each item and renders only supported profile URLs. Invalid items are omitted. Links open in a new tab by default with safe rel values.

<SocialLinks
  links={[
    { platform: "instagram", url: "instagram.com/ahmad" },
    { platform: "github", url: "github.com/ahmad" },
  ]}
  showLabels
  colorStyle="brand"
/>

Customize list, item, link, and icon styling; set newTab; or replace icon/item rendering with renderIcon and renderItem. iconColor takes precedence over colorStyle.

useSocialValidator

A React hook that returns validate, validateOnBlur, reset, result, isValid, error, and touched.

const { validate, validateOnBlur, reset, result, isValid, error, touched } =
  useSocialValidator({
    platform: "github",
    value: url,           // optional automatic validation
    validateOn: "change", // or "blur"
    registry,
    messages,
  });

Use validate for immediate/manual validation, validateOnBlur for touched blur behavior, and reset to clear the result and touched state.

09 / TYPESCRIPT

Types and package entry points

The package includes declaration files for both the core and React entry points. Useful core types include:

PlatformIdBuiltInPlatformIdPlatformDefinitionProfilePathPatternPathProfilePatternQueryProfilePatternUsernameRuleValidationResultValidValidationResultInvalidValidationResultValidationErrorValidationErrorCodeValidationMessagesRegisterPlatformOptionsCreatePlatformRegistryOptions
import type { PlatformDefinition, ValidationResult } from "sociurl";
import type { SocialInputProps, SocialLinksProps } from "sociurl/react";

PlatformId includes the built-in IDs and remains open to custom IDs.

10 / BEHAVIOR & LIMITS

Security, compatibility, and known limits

  • Hostnames are matched exactly; lookalike domains and unlisted subdomains are rejected.
  • Credential-bearing URLs, non-standard ports, raw backslashes, whitespace/control characters, and encoded path separators are rejected.
  • Reserved routes and content pages are not treated as user profiles.
  • Only HTTP and HTTPS are accepted. Normalized links always use HTTPS.
  • Validation does not perform network requests or verify account existence.
Compatibility: Node.js 18 or newer and modern runtimes with the standard URL APIs. The core is React-free and SSR-safe. The optional React entry supports React 18 and React 19.

Platform-specific scope

LinkedIn support covers personal /in/ profiles, not company pages. Medium supports medium.com/@handle, not publication subdomains. Facebook supports vanity paths and numeric profile.php?id= profiles, not every legacy route. YouTube supports handles and common legacy channel paths; short youtu.be links are not profiles.

Package outputs

Published builds include ESM, CommonJS, TypeScript declarations, and source maps. React is external to the React build. The package is tree-shakeable.

READY TO TRY IT?

Explore the API live.

Change the input, create a custom registry, and see the result in the playground.

Open playground ↗