redirect-url
v1.2.1
Published
Simple rule-based redirecting from one URL to another.
Downloads
49
Maintainers
Readme
Features
- Flexible: completely framework agnostic
- Powerful: specify redirects using
path-to-regexp
patterns - Readable: configure using a
Netlify
_redirects
-like syntax
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
const handleRequest = request => {
const result = redirectUrl(request.url)
if (result) {
return redirect(result.url, result.status)
}
// ...
}
export default handleRequest
API
Contributing
Stars are always welcome!
For bugs and feature requests, please create an issue.