Skip to content

feat: use edge function layer for ipx #1880

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 5, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion packages/runtime/src/helpers/edge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export interface FunctionManifest {
cache?: 'manual'
}
>
layers?: Array<{ name: `https://${string}/mod.ts`; flag: string }>
import_map?: string
}

Expand Down Expand Up @@ -345,6 +346,7 @@ export const writeEdgeFunctions = async ({
}) => {
const manifest: FunctionManifest = {
functions: [],
layers: [],
version: 1,
}

Expand Down Expand Up @@ -473,7 +475,12 @@ export const writeEdgeFunctions = async ({
manifest.functions.push({
function: 'ipx',
name: 'next/image handler',
path: '/_next/image*',
path: nextConfig.images.path || '/_next/image',
})

manifest.layers.push({
name: 'https://ipx-edge-function-layer.netlify.app/mod.ts',
flag: 'ipx-edge-function-layer-url',
})
} else {
console.log(
Expand Down
3 changes: 3 additions & 0 deletions packages/runtime/src/templates/edge/imageconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"formats": ["webp"]
}
74 changes: 3 additions & 71 deletions packages/runtime/src/templates/edge/ipx.ts
Original file line number Diff line number Diff line change
@@ -1,73 +1,5 @@
import { Accepts } from 'https://deno.land/x/[email protected]/mod.ts'
import type { Context } from 'https://edge.netlify.com'
// Available at build time
import imageconfig from './imageconfig.json' assert { type: 'json' }

const defaultFormat = 'webp'

interface ImageConfig extends Record<string, unknown> {
formats?: string[]
}

// Checks if a URL param is numeric
const isNumeric = (value: string | null) => Number(value).toString() === value

/**
* Implement content negotiation for images
*/

// deno-lint-ignore require-await
const handler = async (req: Request, context: Context) => {
const { searchParams } = new URL(req.url)
const accept = new Accepts(req.headers)
const { formats = [defaultFormat] } = imageconfig as ImageConfig
if (formats.length === 0) {
formats.push(defaultFormat)
}
let type = accept.types(formats) || defaultFormat
if (Array.isArray(type)) {
type = type[0]
}

const source = searchParams.get('url')
const width = searchParams.get('w')
const quality = searchParams.get('q') ?? '75'
import { getHandler } from 'https://ipx-edge-function-layer.netlify.app/mod.ts'

const errors: Array<string> = []

if (!source) {
errors.push('Missing "url" parameter')
} else if (!source.startsWith('http') && !source.startsWith('/')) {
errors.push('The "url" parameter must be a valid URL or path')
}

if (!width) {
errors.push('Missing "w" parameter')
} else if (!isNumeric(width)) {
errors.push('Invalid "w" parameter')
}

if (!isNumeric(quality)) {
errors.push('Invalid "q" parameter')
}

if (!source || errors.length > 0) {
return new Response(`Invalid request: \n${errors.join('\n')}`, {
status: 400,
})
}

const modifiers = [`w_${width}`, `q_${quality}`]

if (type) {
if (type.includes('/')) {
// If this is a mimetype, strip "image/"
type = type.split('/')[1]
}
modifiers.push(`f_${type}`)
}
const target = `/_ipx/${modifiers.join(',')}/${encodeURIComponent(source)}`
return context.rewrite(target)
}
import imageconfig from './imageconfig.json' assert { type: 'json' }

export default handler
export default getHandler({ formats: imageconfig?.formats })