Skip to content

URL Generation ​

Introduction ​

Hard coding paths in redirects, links and emails makes them brittle. Plinth generates URLs from route names, so you can change a path in one place. It can also produce signed URLs, whose query string carries a tamper proof signature (and optionally an expiry), which is how you build "unsubscribe" links, email verification links and time limited downloads.

URL generation is done by the Router from @plinthjs/http. The router is the same instance you registered routes on.

URLs for named routes ​

Give a route a name, then ask the router for its URL:

ts
import { Router } from '@plinthjs/http'

const router = new Router()
router.get('/users/{id}', showUser).name('users.show')
router.get('/posts/{post}/comments/{comment?}', showComment).name('comments.show')

router.url('users.show', { id: 7 }) // => '/users/7'
router.url('comments.show', { post: 1, comment: 5 }) // => '/posts/1/comments/5'
router.url('comments.show', { post: 1 }) // => '/posts/1/comments' (optional omitted)

Parameter values are URL-encoded, and numbers are accepted. A third argument adds a query string:

ts
router.url('users.show', { id: 7 }, { tab: 'posts', page: 2 })
// => '/users/7?tab=posts&page=2'

Passing an unknown route name, or leaving out a required parameter, throws an error that names the route.

The result is a path. To make an absolute URL, prefix it with the application's origin from your configuration, or with req.schemeAndHttpHost() when you are inside a request:

ts
const absolute = `${req.schemeAndHttpHost()}${router.url('users.show', { id: 7 })}`
// => 'https://acme.test/users/7'

Route parameters in a group prefix are filled the same way, and names work for resource routes, which are called photos.index, photos.show and so on. See Routing.

Use generated URLs for redirects:

ts
import { Response } from '@plinthjs/http'

return Response.redirectTo(router.url('users.show', { id: user.id }))

Inspecting the current URL ​

A Request offers helpers to read and rewrite the URL it arrived on:

ts
req.path() // => '/users/7'
req.url() // => '/users/7?tab=posts'
req.fullUrl() // => 'https://acme.test/users/7?tab=posts'
req.fullUrlWithQuery({ tab: 'comments' }) // replace or add query keys
req.fullUrlWithoutQuery(['tab']) // drop query keys

See Requests.

Signed URLs ​

A signed URL carries a signature query parameter: an HMAC-SHA256 over the path and query string, computed with a secret key. Anyone who changes the path or any query value invalidates the signature, and a recipient cannot forge a URL for a different resource.

First give the router a signing key, normally your application key. Pass it when constructing the router or set it later:

ts
const router = new Router({ key: process.env.APP_KEY })
// or
router.setSigningKey(appKey)

Signing without a key throws an error that tells you to configure one. Generate URLs with signedUrl():

ts
router.get('/unsubscribe/{user}', unsubscribe).name('unsubscribe')

router.signedUrl('unsubscribe', { user: 1 })
// => '/unsubscribe/1?signature=7e286342...'

router.signedUrl('unsubscribe', { user: 1 }, undefined, { ref: 'newsletter' })
// extra query values are part of the signature => '/unsubscribe/1?ref=newsletter&signature=...'

The arguments are the route name, its parameters, an optional expiry, and an optional query object.

Temporary signed URLs ​

Pass an expiry as a Date or as unix seconds, or use temporarySignedUrl() with a lifetime in seconds:

ts
router.temporarySignedUrl('unsubscribe', 3600, { user: 1 }) // valid for one hour
// => '/unsubscribe/1?expires=1794413402&signature=0257a0fe...'

router.signedUrl('download', {}, new Date(Date.now() + 60_000)) // a Date
router.signedUrl('download', {}, Math.floor(Date.now() / 1000) + 300) // unix seconds

The expires value is part of what is signed, so extending it by hand breaks the signature.

Validating signatures ​

In a request handler ​

router.hasValidSignature(req) returns true when the request's path and query carry a correct, unexpired signature:

ts
router.get('/unsubscribe/{user}', (req) => {
  if (!router.hasValidSignature(req)) {
    throw new HttpException(403, 'Invalid or expired link.')
  }
  return 'You are unsubscribed.'
})

With the signed middleware ​

router.signedMiddleware() does the same check as middleware. A missing, wrong or expired signature aborts the request with a 403 and the message Invalid signature., and a valid one passes through:

ts
router
  .get('/unsubscribe/{user}', unsubscribe)
  .name('unsubscribe')
  .middleware(router.signedMiddleware())

Register the middleware on the route that receives the link, not on the one that generates it. You can also alias it, see Middleware:

ts
router.aliasMiddleware('signed', router.signedMiddleware())
router.get('/download/{file}', download).middleware('signed')

Finding out why a URL failed ​

validateSignature(url) takes a path?query string and tells you the reason:

ts
const url = router.temporarySignedUrl('unsubscribe', 3600, { user: 1 })

router.validateSignature(url) // => 'valid'
router.validateSignature('/unsubscribe/1') // => 'missing'
router.validateSignature(url.replace('/1?', '/2?')) // => 'invalid' (tampered)
router.validateSignature(router.signedUrl('unsubscribe', { user: 1 }, 1_000)) // => 'expired'

The four results are valid, missing, invalid and expired. Use them to show a friendlier message, for example offering to resend an expired link.

WARNING

A signed URL proves it was issued by your application. It does not prove who is using it. Anyone holding the link can use it until it expires, so keep lifetimes short for sensitive actions and still check authentication when the action requires it.

When you send your own links by email, build them with temporarySignedUrl(), prefix them with your application origin, and put them in the message. See Mail.

Released under the MIT License.