redirect-url
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

redirect-url

Simple rule-based redirecting from one URL to another.

Features

Install

$ npm i redirect-url

Usage

import { createRedirectUrl, parseRedirectUrl } from 'redirect-url'

let redirectUrl = createRedirectUrl([
  // Nice :)
  [`/bliss`, `https://www.youtube.com/watch?v=dQw4w9WgXcQ`],

  // Other redirects...
  { from: `/home`, to: `/`, status: 307 },
  [`/:splat*\\.html`, `/:splat*`],
])
// OR
redirectUrl = parseRedirectUrl(`
  # Nice :)
  /bliss            https://www.youtube.com/watch?v=dQw4w9WgXcQ

  # Other redirects...
  /home             /          307
  /:splat*\\.html   /:splat*
`)

console.log(redirectUrl(`https://example.com/bliss`))
//=> { url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', status: 302 }
console.log(redirectUrl(`https://example.com/home`))
//=> { url: 'https://example.com', status: 307 }
console.log(redirectUrl(`https://example.com/about-me.html`))
//=> { url: 'https://example.com/about-me', status: 302 }
console.log(redirectUrl(`https://example.com/spaghetti`))
//=> null

This package can be used with any server or framework, but see some example integrations below. Feel free to send pull requests for more examples!

Express

const redirectsMiddleware = (req, res, next) => {
  const result = redirectUrl(req.url)
  if (result) {
    res.redirect(result.status, result.url)
  }
  next()
}

app.all(`*`, redirectsMiddleware)

Remix

entry.server:

export const handleDocumentRequest = request => {
  const result = redirectUrl(request.url)
  if (result) {
    return redirect(result.url, result.status)
  }

  // ...
}

API

See here!

Contributing

Stars are always welcome!

For bugs and feature requests, please create an issue.

For pull requests, please read the contributing guidelines.

License

Apache License 2.0

This is not an official Google product.

Package Sidebar

Install

npm i redirect-url

Weekly Downloads

51

Version

1.1.0

License

Apache-2.0

Unpacked Size

23.8 kB

Total Files

6

Last publish

Collaborators

  • tomeraberbach