↑ ↓ navigate↵ selectesc close

Securing a retail AI endpoint from abuse for virtual try on in Firebase: Web Architecture & Implementation Guide

CodingCat.dev tutorial cover image

Calling frontier multimodal models directly from a web or mobile client is a security minefield if you expose raw API keys or hardcode brittle system prompts in your frontend bundle. Following the announcement of Securing a retail AI endpoint from abuse for virtual try on by Alexander Nohe on the Official Firebase Blog (2025-11-11), here is our hands-on CodingCat.dev breakdown of what actually shipped, how it works under the hood, and how we wire it into production TypeScript, Next.js, Astro, SvelteKit, React, and Angular applications. AI features provide immense value for the end user, but costs money to run. Left unsecured, these features can be abused, but Firebase has multiple ways to protect AI endpoints.

The Mental Model: Why Securing a retail AI endpoint from abuse for virtual try on Matters for Web Devs

As a Google Developer Expert (GDE) for Firebase and Senior Solutions Engineer at CodingCat.dev, I evaluate every Firebase update through one lens: does it reduce boilerplate while keeping our runtime security and cloud bills predictable? Firebase AI Logic lets you invoke Gemini and Imagen models from client and edge apps using the Firebase Web SDK while keeping your API credentials off the wire, enforcing Firebase App Check, and managing server-side prompt templates centrally.

AJ Pro-Tip from Alex: Combine Firebase AI Logic with server prompt templates, Firebase Remote Config feature flags, and project spend caps so you can iterate on prompts or swap Gemini models instantly without redeploying your Next.js or Astro frontend.

How It Works: Technical Breakdown & Implementation

In this example application, I use the nano banana image model to generate a virtual try on experience for shoppers to my website. This app lets shoppers to virtually try on outfits to help better visualize what that outfit would look like on them. This high-value AI endpoint, if unsecured, could lead to prohibitive costs from unlimited outfit generation. The following are measures that were implemented to prevent abuse.

Securing the endpoint from non-authorized clients

We start by securing our endpoint from unauthorized clients. This can help limit the amount of requests that come in via cURL, resellers, and other sites that are not approved to access this endpoint. To do this, we implement App Check, which is designed to help attest that requests to our AI endpoints are coming from real users on real devices. This means that as a user visits our site, You can run a quick attestation in the background and surface the virtual try on button as we test whether the user passes attestation checks. This helps limit the experience to only valid users.

// only show the btn if attestation passes
getLimitedUseToken
  tryOnBtn.style.display 
}).
  console.
});

async
  const
    method: 
    headers: {
      '
      '
      // send latest token
      '
    },
    body: JSON.
  });
}
interface
  auth
    uid
  },
  appCheck
}

const
  let
    auth: {uid: 
    appCheck: 
  }
  const
  const
  if
    const
    const
    context.auth.uid 
  }
  if
    context.appCheck 
  }
  return
}

const

// The tryItOn handler with a context provider to decode firebase context
expressApp.
  '
  expressHandler
    virtualTryOn, {
      contextProvider: firebaseContextProvider
    }
  )
);

Securing the endpoint from replayed requests

Having App Check can help limit our exposure to unauthorized clients, but what if we wanted something that prevented the users from making multiple requests by reusing the same token over and over again? This is where using a replay protected token comes in. In the code displayed above, we make a call to (await getLimitedUseToken(appCheck)).token to append to our request header a fresh, limited-use token. This means that each time we make a request to our endpoint, we request a new token that can be invalidated by the server for replay protected endpoint. Once our server receives the request, we ask App Check to validate and consume the limited-use token by calling verifyToken(appCheckToken, {consume: true}) and App Check will mark the token as having already been consumed.

export
  //... ommitted for brevity
},
async
  if
    throw
  }
  const
    context
    { consume: 
  );
  if
    throw
  }
  //... ommitted for brevity
});

Securing the endpoint from non-authenticated users

While this may seem like a comprehensive solution, we also want to make sure that we don’t just allow any user to make a request to our backend. We should also check whether the user is authenticated and allowed to make these types of requests. In your example App Check code, you may have noticed that we also use the firebaseContextProvider to access the authentication token and extract its uid. If we wanted to check for additional settings, like only allowing email verified users access to this feature, we could additionally make a request to firebaseAuthToken.email_verified and throw an error if the user does not have a verified email.

Securing the endpoint from too many requests by rate limiting

By having authenticated users, we can then additionally apply some rate limiting on those users ourselves. Since we are running our AI inference in a server environment, we can record the number of requests that a user makes in an hour, and place a limit on that number. In the full server side code sample at the end of this post, we’ve included a small function to go and help us rate limit user requests. Using this rate limiter, we can allow requests as long as they do not exceed the maximum number of requests within one hour. Having this reset each hour allows customers to come back and continue using our site. We can also surface this error to the users letting them know that in one hour they can try again. Any third party rate limiting tool can be used here.

Limiting the input into our virtual try on function

Finally, as a best practice, we limit what the API endpoint accepts. If someone were to reconstruct the request and try to pass in their own inputs, we could potentially have our AI system serve results that would not be for their originally intended purpose. For instance, if we accept two images and a prompt as the input, the end user may insert their own images as well as their own prompt, effectively exploiting the API surface for their own means. With our implementation, we limit requests to just the sku. The server is then responsible for fetching the user uploaded profile image, the product sku image, and the prompt associated with that sku. This helps limit prompt injection attacks since the end user cannot insert custom language into the image generator or their own images outside of their profile image into the image generator.

import
import
import
import
import
import
import
import
import
import
import
import

const
  projectId: firebaseConfig.projectId,
  storageBucket: firebaseConfig.storageBucket
});

/** start rate limiter */
const
const
const
const
const

const
  return
};

const
  const
  date.
  return
};

const
  const
  date.
  return
};

const
  userId
  tokens 
) 
  return
    const
    return
      userRateCollection.
      {
        [TOKEN_FIELD]: tokens,
        [REQUEST_TIME_FIELD]: Timestamp.
        [TTL_FIELD]: 
      });
  });
};

const
  return
    const
    const
      REQUEST_TIME_FIELD, 
    const

    return
      return
    });
  });
};

const
  const
  if
    return
  }
  await
  return
};

/** end rate limiter */

// Initialize Genkit with the Vertex AI plugin
const
  plugins: [
  model: vertexAI.
    temperature: 
  }),
});

// Define input schema
const
  productSku: z
    .
    .
});

const
  virtualTryOnOutputUrl: z
    .
    .
});

export
  name: 
  inputSchema: VirtualTryOnInputSchema,
  outputSchema: VirtualTryOnSchema
},
  async
    console.
    // const context = {auth: {uid: "1"}};
    if
      throw
    }

    if
      throw
    }

    const
        context
    );
    if
      throw
    }

    const
    if
      return
    }

    if
      throw
      "
    }

    const
    const
    const

    const
      model: vertexAI.
      prompt: [
        { media: { url: productImg.url } },
        { media: { url: userImg.url } },
        { text: imageGenPrompt }
      ],
      output: { format: 
    });

    if
      const
      if
        await
        return
      }
    }

    throw

  });

async
    parsed
    uid
  if
    throw
  }
  const
  const
  const
  const

  await
    metadata: {
      contentType: parsed.mimeType.essence,
    },
  });
}

async
  const
  const
  const
  const
  const
  return
    url: 
  };
}

async
  const
  const
    await
  if
    throw
        '
  }
  const
  const
  const
  const
  return
    url: 
  };
}

async
  const
  const
  if
    throw
        '
  }

  const
  if
    throw
        '
  }
  return
}

async
    uid
  const
  const
  const

  if
    return
  }

  const
  const
    [img
  const

  return
    url: 
  };
}

interface
  auth
    uid
  },
  appCheck
}

const
    req
  let
    auth: {uid: 
    appCheck: 
  }
  console.
  const
  const
  if
    const
    const
    context.auth.uid 
  }
  if
    context.appCheck 
  }
  return
}

const
expressApp.
expressApp.

expressApp.
  '
  expressHandler
    virtualTryOn, {
      contextProvider: firebaseContextProvider
    }
  )
);

expressApp.
  console.
});

Production Web Architecture & Security Checklist

Whether we are deploying on Firebase App Hosting, Cloudflare Workers, or Vercel, shipping AI features to production requires defense-in-depth across three layers:

  • Enforce Firebase App Check & Attestation: Protect your web endpoints, Cloud Functions, Data Connect GraphQL resolvers, and Firebase AI Logic calls against unauthorized replay or billing abuse using Firebase App Check with reCAPTCHA Enterprise.
  • Validate Locally with the Firebase Emulator Suite: Run deterministic integration tests against local Firestore, Auth, Functions, and Data Connect PostgreSQL emulators before promoting schema or rule changes to production.
  • Keep Server & Client Boundaries Type-Safe: Use the modular Firebase Web SDK and generated TypeScript bindings so SSR frameworks like Next.js, Astro, SvelteKit, and Angular serialize state cleanly without hydration flickers.

Conclusion

Accelerate your full-stack web and AI development by pairing Securing a retail AI endpoint from abuse for virtual try on with strict Security Rules, Firebase App Check, and local emulator testing. Come tell us on X (@CodingCatDev) and LinkedIn (CodingCat.dev) how you are using Firebase in your stack, and subscribe to the CodingCat.dev YouTube Channel so you don't miss what we build next!

Watch Our Related Firebase Video Tutorial on YouTube

Want to see how we architect and debug Firebase web applications live? Watch our related CodingCat.dev session Firebase Security Rules: Effortless control over your app's data. below, and make sure to Subscribe to CodingCat.dev on YouTube for weekly full-stack web and AI deep dives:

Resources, Official Docs & Related CodingCat.dev Guides

Frequently Asked Questions (FAQ)

What are the key capabilities introduced in Securing a retail AI endpoint from abuse for virtual try on?

Securing a retail AI endpoint from abuse for virtual try on (announced 2025-11-11 by the Firebase team) enhances the platform for Firebase, Google Cloud, Web Dev, AI, Security workloads. AI features provide immense value for the end user, but costs money to run. Left unsecured, these features can be abused, but Firebase has multiple ways to protect AI endpoints. Developers can review the primary announcement on the Firebase Blog alongside our implementation patterns and production checklist above.

How do web developers use Securing a retail AI endpoint from abuse for virtual try on with Next.js, SvelteKit, React, or Angular?

Web developers can integrate these features using the modular Firebase JavaScript/TypeScript SDK, Firebase Data Connect web bindings, and Firebase App Hosting. Always pair client-side SDK initialization with Firebase App Check and strict Security Rules, and test locally with the Firebase Local Emulator Suite before deploying.

Where can I watch video tutorials on Firebase Web and AI development?

You can watch our hands-on Firebase video walkthroughs on the CodingCat.dev YouTube Channel, including Firebase Security Rules: Effortless control over your app's data., and follow us on X (@CodingCatDev) for weekly full-stack tutorials.