Skip to content

Polka does not support unicode in routing patterns. #187

@aral

Description

@aral

The problem

Polka does not support unicode in routing patterns.

(Routing fails when unicode – e.g., emoji or an ü, etc. – is included in the routing pattern.)

Basic reproduction

import polka from 'polka'

polka()
  .get('/kitten', (_request, response) => response.end('Meow!'))
  .get('/😸', (_request, response) => response.end('Meow!'))
  .listen(3000, _ => {
    console.log('Visit http://localhost:3000/kitten (works)')
    console.log('and http://localhost:3000/😸 (doesn’t work).')
  })

I’m assuming this is actually an issue in trouter, so going to try and reproduce there now but opening the issue here since it’s the main project that’s impacted.

Nope, the bug is in Polka, not trouter:

import Trouter from 'trouter'

const router = new Trouter()

router
  .get('/kitten', _ => {
    console.log('Meow from plain text route path!')
  })
  .get('/😸', _ => {
    console.log('Meow from emoji route path!')
  })

// Find a route definition
const kittenText = router.find('GET', '/kitten')
const kittenEmoji = router.find('GET', '/😸')

// Both handlers execute as expected.
kittenText.handlers[0]()
kittenEmoji.handlers[0]()

You can replace the Kitten emoji with the letter ü and observe the same behaviour.

Workaround

You must manually URI encode every component of the file path before adding your route to the router. Unless I’m mistaken, this is basically what SvelteKit does also (see sveltejs/kit#2171).

So here’s the above example, with the workaround implemented:

import path from 'node:path'
import polka from 'polka'

const encodeFilePath = filePath => filePath
  .split(path.sep)
  .map(value => encodeURIComponent(value))
  .join(path.sep)

polka()
  .get(encodeFilePath('/kitten'), (_request, response) => response.end('Meow!'))
  .get(encodeFilePath('/😸'), (_request, response) => response.end('Meow!'))
  .listen(3000, _ => {
    console.log('Visit http://localhost:3000/kitten (works)')
    console.log('and http://localhost:3000/😸 (now also works).')
  })

Suggested solution

Based on the above workaround, Polka itself should apply the equivalent of the encodeFilePath() function internally and transparently when .get(), etc., is called.

Please let me know if you’d like a pull request for this; I’d be happy to prepare one.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions