parse-url is a JavaScript/TypeScript library designed for advanced URL parsing, notably providing robust support for various Git URL formats (e.g., `git+ssh://`, `git@github.com`). It goes beyond standard URL parsing by offering detailed breakdown into components like protocols, resource, user, pathname, hash, search, and query object. The current stable version is 11.1.0, with a release cadence that includes major version updates roughly annually and more frequent minor/patch releases to address issues and update dependencies. A key differentiator is its explicit handling of Git URLs and the ability to control URL normalization via options passed to the underlying `normalize-url` library, offering more granular control than built-in or simpler parsers.
npm install parse-urlVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to parse various URL formats, including standard HTTP(S) URLs with query strings and hashes, and complex Git SSH URLs, highlighting the use of the `normalize` parameter.
Review the changelog for `normalize-url` version 9.0.0 if unexpected URL normalization behavior is observed. Test existing code paths that rely on URL normalization carefully after upgrading.
If parsing of Git SSH URLs with spaces in paths is critical, ensure to test against version 9.0.0 or later. For older versions, manual pre-processing of such URLs might be necessary.
Always wrap calls to `parseUrl` in a `try...catch` block if the input URL might be malformed or invalid to prevent application crashes.
Be mindful of the `normalize` parameter's default value. Pass `true` for general normalization or an object for specific `normalize-url` options. For Git URLs, it's often best to set `normalize: false` to preserve their specific structure.
For ESM, use `import parseUrl from 'parse-url';`. For CommonJS, ensure your `tsconfig.json` (if using TypeScript) and bundler are configured for ESM output, or try `const parseUrl = (await import('parse-url')).default;` if using dynamic import in CJS.Ensure the input URL string is well-formed. Use a `try...catch` block around `parseUrl` calls to gracefully handle and log invalid inputs, or perform basic input validation beforehand.
Ensure you are using `import type { ParseUrlResult } from 'parse-url';` and explicitly typing the result, e.g., `const parsed: ParseUrlResult = parseUrl(someUrl);` to leverage the provided TypeScript definitions.