Skip to content

Instantly share code, notes, and snippets.

@jbmoelker
Created October 10, 2017 18:30
Show Gist options
  • Save jbmoelker/d735573f9f5fb049d894f4ea2e13132c to your computer and use it in GitHub Desktop.
Save jbmoelker/d735573f9f5fb049d894f4ea2e13132c to your computer and use it in GitHub Desktop.
Serve placeholder images with Client Hints (DPR, Width, Viewport Width) as text
const request = require('request')
module.exports = () => (req, res, next) => {
const dpr = parseFloat(req.headers.dpr)
const width = toInteger(req.headers.width)
const viewportWidth = toInteger(req.headers['viewport-width'])
const imageWidth = width || Math.round(viewportWidth * dpr)
const imageHeight = Math.round(imageWidth/2)
request(`http://via.placeholder.com/${imageWidth}x${imageHeight}?text=` + [
`DPR: ${dpr}`,
`W: ${width ? width : '?'}`,
`VPW: ${viewportWidth}`
].join(', '))
.pipe(res)
}
function toInteger(value) {
const int = parseInt(value, 10)
return isNaN(int) ? undefined : int
}
const clientHintsAsImage = require('./client-hints-as-image');
const express = require('express');
const app = express();
app.use(/.*\.(jpg|png)/, clientHintsAsImage());
app.listen(process.env.PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment