Possible to rewrite subpath to different origin?

I have a frontend deployed to Cloudflare pages with an alias at https://example.com
I have a backend proxied via Cloudflare (Full Strict) to my own server at https://api.example.com

This works fine, but I would like them to be on the same origin.

Ideally I would map

https://example.com/api/path/to/resource to https://api.example.com/path/to/resource

I tried the following by adding a _worker.js to my Cloudflare pages (code provided below). But I was wondering if there was a better way?

export default {
  async fetch(request, env) {
    const url = new URL(request.url)

    if (url.pathname.startsWith('/api/')) {
      url.hostname = 'api.example.com'
      url.pathname = url.pathname.replace(/^\/api/, '')

      const newRequest = new Request(url, {
        body: request.body,
        headers: request.headers,
        method: request.method,
        redirect: request.redirect,

      return await fetch(newRequest)
    // Otherwise, serve the frontend assets.
    return env.ASSETS.fetch(request)