Using function as a proxy

Hey! Is it possible to have a function living, for example, at /functions/index.js to take an action before resolving the request? Something like:

const destinationURL = 'https://startpage.com'
const statusCode = 301

export async function onRequest(context) {
  const { request } = context

  const url = new URL(request.url)

  if (url.pathname.startsWith('/test')) {
    return Response.redirect(destinationURL, statusCode)
  }

  return Response
}

The above obviously does not work but what I mean is:

  1. check if the url path starts with /test
  2. if so, redirect to startpage.com
  3. if it does not, server the page as normal

Hi, take a look at Middleware routing, if you create the file functions/_middleware.js, it’ll apply to all routes, and you can check for the path.

export async function onRequest(context) {
  const {
    request, // same as existing Worker API
    env, // same as existing Worker API
    params, // if filename includes [id] or [[path]]
    waitUntil, // same as ctx.waitUntil in existing Worker API
    next, // used for middleware or to fetch assets
    data, // arbitrary space for passing data between middlewares
  } = context
  const res = await next()
  const { pathname } = new URL(request.url)

  if (pathname === '/test') {
    return new Response.redirect('http://example.com', '307')
  }

  return res
}

Cheers, that’s exactly what I was after!

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.