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

1.2.1 • 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:

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

  // ...
}

export default handleRequest

API

See here!

Contributing

Stars are always welcome!

For bugs and feature requests, please create an issue.

License

MIT © Tomer Aberbach
Apache 2.0 © Google

Dependents (0)

Package Sidebar

Install

npm i redirect-url

Weekly Downloads

155

Version

1.2.1

License

Apache-2.0 AND MIT

Unpacked Size

25.1 kB

Total Files

8

Last publish

Collaborators

  • tomeraberbach