Skip to content

Instantly share code, notes, and snippets.

@moander
Last active March 10, 2024 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moander/6f4fb4c1ca89a144794d6e46a3e85874 to your computer and use it in GitHub Desktop.
Save moander/6f4fb4c1ca89a144794d6e46a3e85874 to your computer and use it in GitHub Desktop.
_worker.js for pages api
/* eslint-disable */
/**
* Add _worker.js to your public directory to enable /api/* proxying
*
* env.API_ROUTER_URL
* Requests to /api/* is proxied to this url
*
* env.API_ROUTER_STRIP_PREFIX
* Remove this part from the beginning of pathname before proxying
* Useful if you need to hide /api/ from the backend. (GET /api/test -> GET /test)
*
* env.ROBOTS_TXT
* Set to 'allow' to return User-agent: * Allow: /
*
* env.ROBOTS_TXT_OVERRIDE
* Return this text for /robots.txt
*
* env.FIREBASE_AUTH_PROJECT
* Set to Google Identity Platform / Firebase Auth project id.
* This is useful for signInWithRedirect (authDomain=origin)
*
* wget https://gist.githubusercontent.com/moander/6f4fb4c1ca89a144794d6e46a3e85874/raw/_worker.js
*/
export default {
async fetch(request, env) {
const url = new URL(request.url)
if (url.pathname.startsWith('/api/')) {
if (!env.API_ROUTER_URL) {
return new Response('env.API_ROUTER_URL is required', { status: 500 })
}
let pathname = url.pathname
if (env.API_ROUTER_STRIP_PREFIX && pathname.startsWith(env.API_ROUTER_STRIP_PREFIX)) {
pathname = pathname.substring(env.API_ROUTER_STRIP_PREFIX.length)
}
const proxyToUrl = env.API_ROUTER_URL + pathname + url.search + url.hash
return await proxyTo(proxyToUrl, request)
}
else if (url.pathname.startsWith('/robots.txt')) {
let output = 'User-agent: *\nDisallow: /\n'
if (env.ROBOTS_TXT === 'allow') {
output = 'User-agent: *\nAllow: /\n'
}
if (env.ROBOTS_TXT_OVERRIDE) {
output = env.ROBOTS_TXT_OVERRIDE?.toString().replaceAll('\\n', '\n').trim() || output
}
return new Response(output, {
headers: { 'Content-Type': 'text/plain' },
})
}
else if (url.pathname.startsWith('/__/auth/')) {
if (!env.FIREBASE_AUTH_PROJECT) {
return new Response('env.FIREBASE_AUTH_PROJECT is required', { status: 500 })
}
const proxyToUrl = `https://${env.FIREBASE_AUTH_PROJECT}.firebaseapp.com` + url.pathname + url.search + url.hash
return await proxyTo(proxyToUrl, request)
}
return env.ASSETS.fetch(request)
},
}
async function proxyTo(proxyToUrl, request) {
return await fetch(proxyToUrl, {
method: request.method,
headers: request.headers,
body: request.body,
}).catch(err => {
console.error('proxyError', JSON.stringify({ message: err.message, proxyToUrl }))
return Response.json({ message: `API proxy error: ${err.message}` }, {
status: 502,
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment