|
| 1 | +# Preact ISO URL Pattern Matching - Polyglot Utils |
| 2 | + |
| 3 | +Multi-language implementations of URL pattern matching utilities for building bespoke server setups that need to preload JS/CSS resources or handle early 404 responses. |
| 4 | + |
| 5 | +## Use Case |
| 6 | + |
| 7 | +This utility is designed for server languages that **cannot do SSR/prerendering** but still want to provide better experiences. It enables servers to: |
| 8 | + |
| 9 | +- **Add preload head tags** for JS,CSS before serving HTML |
| 10 | +- **Return early 404 pages** for unmatched routes |
| 11 | +- **Generate dynamic titles** based on route parameters |
| 12 | + |
| 13 | +## How can I implement preloading of JS, CSS? |
| 14 | + |
| 15 | +Typical implementation flow: |
| 16 | + |
| 17 | +1. **Build-time Setup:** |
| 18 | + - Write your routes as an array in a JS file |
| 19 | + - Create a build script that exports route patterns and entry files to a `.json` file |
| 20 | + - Configure your frontend build tool to output a `manifest` file mapping entry files to final fingerprinted/hashed output JS/CSS files and dependencies |
| 21 | + |
| 22 | +2. **Server-time Processing:** |
| 23 | + - Load the JSON route file when a request comes in |
| 24 | + - Match the requested URL against each route pattern until you find a match |
| 25 | + - Once matched, you have the source entry `.jsx` file |
| 26 | + - Load the build manifest file to find which JS chunk contains that code and its dependency files |
| 27 | + - Generate `<link rel="preload">` tags for each dependency (JS, CSS, images, icons) |
| 28 | + - Inject those head tags into the HTML before serving |
| 29 | + |
| 30 | +3. **Result:** |
| 31 | + - Browsers start downloading critical resources immediately |
| 32 | + - Faster page loads without full SSR complexity |
| 33 | + - Early 404s for invalid routes |
| 34 | + |
| 35 | +### Example - preloading of JS, CSS |
| 36 | + |
| 37 | +Here's how you might integrate this into a server setup. Let's say you have a client side `routes.js` as follows: |
| 38 | + |
| 39 | +```js |
| 40 | +import { lazy } from 'preact-iso'; |
| 41 | + |
| 42 | +export const routes = [ |
| 43 | + { |
| 44 | + "path": "/users/:userId/posts", |
| 45 | + "component": lazy(() => import("pages/UserPosts.jsx")), |
| 46 | + "title": "Posts by :userId" |
| 47 | + }, |
| 48 | + { |
| 49 | + "path": "/products/:category/:id", |
| 50 | + "component": lazy(() => import("pages/Product.jsx")), |
| 51 | + "title": "Product :id" |
| 52 | + } |
| 53 | +]; |
| 54 | +``` |
| 55 | + |
| 56 | +1. **Generate Routes JSON (routes.json)** |
| 57 | + |
| 58 | +You can use the following standalone node.js script to create `routes.json` during build (you could convert it into a plugin for your frontend build tool): |
| 59 | +```js |
| 60 | +const routeDir = path.resolve(__dirname, 'client/src/routes'); |
| 61 | +let routesFile = fs.readFileSync(path.resolve(routeDir, 'routes.js'), 'utf-8'); |
| 62 | +routesFile = routesFile.replace(/lazy\s*\(\s*\(\s*\)\s*=>\s*import\s*\(\s*(.+)\s*\)\s*\)\s*(,?)/g, '$1$2'); |
| 63 | +const fileName = path.resolve(__dirname, 'routes-temp.js') |
| 64 | +fs.writeFileSync(fileName, routesFile, 'utf-8'); |
| 65 | +const routes = (await import(fileName)).default; |
| 66 | +fs.unlinkSync(fileName); |
| 67 | +const routeInfo = routes.map((route) => ({ |
| 68 | + path: route.path, |
| 69 | + title: typeof route.title === 'string' ? route.title : null, |
| 70 | + Component: path.relative(__dirname, path.resolve(routeDir, `${route.Component}.jsx`)), |
| 71 | + default: route.default, |
| 72 | +})); |
| 73 | +// console.log(routeInfo); |
| 74 | +fs.writeFileSync( |
| 75 | + path.resolve(__dirname, 'dist/routes.json'), |
| 76 | + JSON.stringify(routeInfo, null, 2), |
| 77 | + 'utf-8' |
| 78 | +); |
| 79 | +``` |
| 80 | + |
| 81 | +The script produces the following `routes.json` file: |
| 82 | +```json |
| 83 | +[ |
| 84 | + { |
| 85 | + "path": "/users/:userId/posts", |
| 86 | + "component": "pages/UserPosts.jsx", |
| 87 | + "title": "Posts by :userId" |
| 88 | + }, |
| 89 | + { |
| 90 | + "path": "/products/:category/:id", |
| 91 | + "component": "pages/Product.jsx", |
| 92 | + "title": "Product :id" |
| 93 | + } |
| 94 | +] |
| 95 | +``` |
| 96 | + |
| 97 | +2. **Build Manifest (manifest.json)** |
| 98 | + |
| 99 | +This is the file your client build tool generates. Check your build tool's documentation for exact format. Below is an example with few important fields from a Vite manifest file: |
| 100 | +```json |
| 101 | +{ |
| 102 | + "pages/UserPosts.jsx": { |
| 103 | + "file": "assets/UserPosts-abc123.js", |
| 104 | + "css": ["assets/UserPosts-def456.css"], |
| 105 | + "imports": ["chunks/shared-ghi789.js"] |
| 106 | + } |
| 107 | +} |
| 108 | +``` |
| 109 | + |
| 110 | +3. **Server Implementation** |
| 111 | +```python |
| 112 | +# Python example |
| 113 | +import json |
| 114 | + |
| 115 | +routes = json.load(open('../dist/routes.json')) |
| 116 | +manifest = json.load(open('../dist/.vite/manifest.json')) |
| 117 | + |
| 118 | +def handle_request(url_path): |
| 119 | + for route in routes: |
| 120 | + matches = preact_iso_url_pattern_match(url_path, route['path']) |
| 121 | + if matches: |
| 122 | + # Generate preload tags |
| 123 | + component = route['component'] |
| 124 | + entry_info = manifest[component] |
| 125 | + |
| 126 | + preload_tags = [] |
| 127 | + for js_file in [entry_info['file']] + entry_info.get('imports', []): |
| 128 | + preload_tags.append(f'<link rel="modulepreload" crossorigin href="{js_file}">') |
| 129 | + |
| 130 | + for css_file in entry_info.get('css', []): |
| 131 | + preload_tags.append(f'<link rel="stylesheet" crossorigin href="{css_file}">') |
| 132 | + |
| 133 | + # Generate dynamic title |
| 134 | + title = route['title'] |
| 135 | + for param, value in matches['params'].items(): |
| 136 | + title = title.replace(f':{param}', value) |
| 137 | + |
| 138 | + return { |
| 139 | + 'preload_tags': preload_tags, |
| 140 | + 'title': title, |
| 141 | + 'params': matches['params'] |
| 142 | + } |
| 143 | + |
| 144 | + # No match found - return early 404 |
| 145 | + return None |
| 146 | +``` |
| 147 | + |
| 148 | +This approach gives you the performance benefits of resource preloading without the complexity of full server-side rendering. |
| 149 | + |
| 150 | +## Available Languages |
| 151 | + |
| 152 | +Go, PHP, Python and Ruby. |
| 153 | + |
| 154 | +Find the corresponding language's sub-directory. Each language has a README that contains usage examples and API reference. |
| 155 | + |
| 156 | +## Running Tests |
| 157 | + |
| 158 | +```bash |
| 159 | +# Run all tests across all languages |
| 160 | +./run_tests.sh |
| 161 | + |
| 162 | +# Or run individual language tests |
| 163 | +cd go && go test -v |
| 164 | +cd python && python3 test_preact_iso_url_pattern.py |
| 165 | +cd ruby && ruby test_preact_iso_url_pattern.rb |
| 166 | +cd php && php test_preact_iso_url_pattern.php |
| 167 | +``` |
0 commit comments