ezsite.ai › Blog › How Do I Add Serverless Functions to a Cloned Website for Custom API Endpoints?
← All articlesHow Do I Add Serverless Functions to a Cloned Website for Custom API Endpoints?
Key takeaways
- Use a five-step path: clone the site, create the function, configure access, implement and test it, then connect the published URL from the frontend.
- Keep the cloned UI intact while replacing mock data or client-only actions with explicit request and response contracts.
- Anonymous, authenticated, API-key, and webhook endpoints use different authorization mechanisms and must enforce them inside the function.
- Never expose provider secrets or privileged API keys in browser code; store them in server-side environment or secret configuration.
- Handle CORS, HTTP methods, status codes, malformed JSON, missing secrets, upstream timeouts, and payload limits before production.
- Stay in EZsite for an integrated workflow; export when your team needs custom infrastructure, runtime control, or an existing deployment pipeline.

Add backend behavior to a cloned website by connecting its existing forms and UI actions to a server-side HTTP function. The frontend remains responsible for pages and interaction; the function validates requests, performs trusted work, accesses protected services, and returns structured JSON.
Five-step implementation path
1. Clone the website and identify the form, button, page, or mock-data call that needs backend behavior.
2. Create a function in EZsite or your chosen deployment platform.
3. Configure access as anonymous, authenticated, API-key protected, or webhook-verified.
4. Implement and test the request validation, authorization, business logic, response format, CORS behavior, and error paths.
5. Call the published URL from the cloned frontend and replace the existing mock or client-only implementation.
How do I add a function to a cloned website?
Add a function by defining an HTTP contract, implementing the server-side action, publishing it, and replacing the clone’s client-side mock request with a fetch() call to the published URL.
Use this architecture:
- Cloned frontend: renders pages, collects input, manages loading and error states, and displays results.
- Backend function: validates input, authorizes the caller, accesses databases or third-party services, and keeps provider secrets out of browser code.
- HTTP contract: defines the method, path, request JSON, response JSON, status codes, and access rules.
For a cloned contact page, preserve the current form and confirmation screen while replacing the mock submit handler with a function contract such as:
```json
{
"email": "visitor@example.com",
"message": "Please contact me about the product."
}
```
Return predictable JSON:
```json
{
"success": true,
"message": "Your message was received."
}
```
Use 400 for malformed or invalid input, 401 when authentication is missing, 403 when the caller is authenticated but not allowed to perform the action, 404 for a missing resource, 409 for a business conflict, 502 for an upstream service failure, and 500 for an unexpected server error.
How do I create a custom API endpoint in EZsite?
In EZsite, open the project’s Settings, select Edge Function, choose + Create Function, enter a name and description, select the access mode, and create the function. (ezsite.ai)
After creating it, open the function’s Code Editor to edit or generate code, use Update Function to save changes, and use Test to run the function. The Basic Configuration tab contains API Call Examples, including the endpoint and sample cURL, JavaScript, and Python requests. (ezsite.ai)
Choose the access model
| Access model | Caller credential or verification | Authorization rule | Suitable use |
|---|---|---|---|
| Anonymous | No caller identity is required | Enforce validation, rate controls, and abuse protection inside the function | Public contact forms or non-sensitive public data |
| Authenticated | A user or session access token | Validate the token and authorize access to the requested user or resource | Profiles, orders, dashboards, and account actions |
| API-key protected | A client or service API key | Compare the supplied key with a server-side configured value or use the platform’s authorization mechanism | Controlled internal tools or server-to-server calls |
| Webhook receiver | Provider signature, signing secret, or verification token | Verify the raw request signature or provider token before parsing or processing the event | Payments, CRM events, and automation callbacks |
Anonymous access does not make an operation safe by itself: the function must still validate input, limit abuse, and avoid exposing private data. An API key used by browser code is not a secret because visitors can inspect it; privileged provider keys belong only in server-side environment or secret storage.
EZsite’s official guide documents custom endpoints, external-service connections, webhook handling, synchronization workflows, database access, endpoint generation, API examples, and authorization-key creation. (ezsite.ai)
Can I generate the function with AI?
Yes, EZsite can generate an Edge Function from a detailed prompt, after which you should inspect the code, update it, and test both successful and rejected requests. (ezsite.ai)
A useful generation prompt specifies:
1. Method and request: POST with email and message fields.
2. Validation: required fields, maximum lengths, and accepted formats.
3. Authorization: anonymous, user-token, API-key, or webhook-signature access.
4. Action: create a lead, query a record, call a provider, or update an order.
5. Response: exact JSON fields and status codes.
6. Failure handling: malformed JSON, missing secrets, rejected authorization, and upstream timeouts.
For example:
> Create a POST function for a cloned contact form. Parse JSON, require a valid email and a message between 1 and 2,000 characters, reject invalid requests with status 400, create a lead record, return { success: true, message: "Received" } with status 200, and return structured errors without exposing provider credentials.
The documented built-in database example uses Product and Order tables and demonstrates retrieving products associated with orders from a specified month. The value of the example is its request-to-database-to-JSON pattern, not the particular month used in the sample. (ezsite.ai)
What should the backend implementation look like?
A minimal implementation should parse the request, restrict the method, validate fields, perform the trusted action, return JSON, and handle expected failures without leaking internal details.
```js
function json(body, status = 200, extraHeaders = {}) {
return new Response(JSON.stringify(body), {
status,
headers: {
"Content-Type": "application/json",
...extraHeaders
}
});
}
export default async function handler(request) {
if (request.method === "OPTIONS") {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "https://your-cloned-site.example",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization"
}
});
}
if (request.method !== "POST") {
return json({ success: false, error: "Method not allowed" }, 405);
}
try {
const body = await request.json();
const email = typeof body.email === "string" ? body.email.trim() : "";
const message = typeof body.message === "string" ? body.message.trim() : "";
if (!/^\S+@\S+\.\S+$/.test(email) || message.length < 1 || message.length > 2000) {
return json({ success: false, error: "Invalid form data" }, 400);
}
// Replace this with a database insert or provider request.
// Read any provider secret from the platform's server-side secret store here.
const lead = { email, message, receivedAt: new Date().toISOString() };
return json(
{ success: true, message: "Your message was received.", data: lead },
200,
{ "Access-Control-Allow-Origin": "https://your-cloned-site.example" }
);
} catch {
return json({ success: false, error: "Malformed JSON or server error" }, 400);
}
}
```
The handler shape above is a portable Request/Response pattern; adapt the export and secret-access syntax to the runtime that receives the generated EZsite code. Store values such as CRM_API_KEY, EMAIL_PROVIDER_KEY, or WEBHOOK_SIGNING_SECRET in the platform’s encrypted server-side environment configuration, never in the cloned frontend bundle.
How do I call the function from React or Vue?
Call the published function URL from the existing form action and send only user input or a user/session credential that the browser is allowed to possess.
```js
async function submitContactForm({ email, message, sessionToken }) {
const headers = {
"Content-Type": "application/json"
};
// This must be a user/session token for the signed-in user,
// not a provider secret or privileged server API key.
if (sessionToken) {
headers.Authorization = Bearer ${sessionToken};
}
const response = await fetch("https://your-function-endpoint.example", {
method: "POST",
headers,
body: JSON.stringify({ email, message })
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(data.error || Request failed with status ${response.status});
}
return data;
}
```
For an anonymous contact form, omit the Authorization header and enforce validation and abuse controls in the function. For a protected application request, send the current user’s session or access token and authorize that user inside the function. For a provider API call, send no provider credential from the browser; the function retrieves the provider secret server-side.
EZsite’s API Call Examples panel supplies the function URL and example requests, while its guide documents authorization API-key creation for protected calls. (ezsite.ai)
How do CORS, deployment, methods, and payloads work?
A browser can call the published function only when the function’s CORS response permits the cloned site’s origin, and the function must explicitly handle the HTTP methods and payload sizes required by the feature.
Use these operational rules:
- Endpoint URL: copy the URL shown in the function’s Basic Configuration or API Call Examples area.
- Publishing: save the function, publish or deploy the project, and call the deployed URL from the frontend.
- Methods: use
GETfor safe reads,POSTfor creation or actions,PUTorPATCHfor updates, andDELETEfor deletion. - CORS: respond to browser preflight
OPTIONSrequests and allow only the cloned site’s known origin in production. - Headers: return
Content-Type: application/jsonfor JSON responses and allow only the request headers the browser needs. - Status codes: make success and failure status meaningful so the frontend can handle them without parsing error text.
- Payloads: keep JSON requests concise; send large files directly to object storage rather than through a small API body.
- Timeouts: set bounded waits for third-party requests and return a controlled
502or retry response when an upstream service does not respond.
EZsite’s guide exposes the generated endpoint and client examples through the function configuration interface. Exported platforms apply their own runtime, payload, duration, and routing limits; for example, Vercel documents a 4.5 MB request-or-response body limit for Vercel Functions, while Netlify documents method configuration, paths, background execution, and standard Request/Response handlers. (ezsite.ai)
What should a function handle for a cloned website?
A function should handle trusted operations that the browser cannot safely perform, while the clone should retain the current visual experience and delegate only the data or integration action to the backend.
Product-specific patterns include:
- Existing form replacement: keep the clone’s fields and validation messages, then map its submit payload to the function’s request schema.
- Mock-data replacement: preserve the current cards, tables, and loading states while replacing hard-coded arrays with a
GETrequest. - Lead capture: validate the form, create a CRM record, and send an acknowledgement through a server-side provider integration.
- Order lookup: accept a customer-authorized identifier, query order data, and return only records the caller may view.
- Third-party proxy: keep shipping, email, payment, analytics, or AI provider credentials in server-side secrets.
- Webhook processing: verify the provider signature before parsing the event, make processing idempotent, and return quickly.
- Synchronization: translate the clone’s data model into the CRM, database, or operational system’s schema.
EZsite’s Edge Function guide specifically describes custom APIs, external integrations, webhooks, synchronization, and built-in database access as supported use cases. (ezsite.ai)
How do I test and troubleshoot the endpoint?
Test the function independently before wiring it into the live clone, then test the browser integration with valid input, invalid input, missing credentials, authorization failures, and upstream failures.
Test checklist
1. Run the platform’s function test with a valid request body.
2. Repeat with missing fields, invalid JSON, oversized values, and unsupported methods.
3. Test anonymous, authenticated, API-key, and webhook-verification paths separately.
4. Run the generated cURL example to distinguish backend failures from frontend issues.
5. Open the browser network panel and inspect the request URL, method, preflight request, status, and response body.
6. Test provider timeouts and duplicate webhook delivery before production use.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
401 Unauthorized | Missing, expired, or malformed user/session credential | Send the correct session token and validate it in the function |
403 Forbidden | The caller is authenticated but lacks permission | Enforce ownership, role, or resource-level authorization |
| CORS error | The function does not allow the cloned site’s origin or headers | Handle OPTIONS and return the correct CORS headers |
| Malformed JSON | Empty body, wrong Content-Type, or invalid serialization | Send JSON.stringify(payload) and parse errors explicitly |
| Missing environment variable | Secret was not configured for the deployed environment | Add it to server-side environment settings and redeploy |
| Third-party timeout | Provider is slow, unavailable, or blocked | Use an explicit timeout, return 502, and add safe retry or queue logic |
| Works in Test but not in browser | Different origin, headers, credentials, or deployment version | Reproduce with cURL, inspect preflight, and confirm the published URL |
Should I use EZsite Edge Functions or export the cloned app to another platform?
Use EZsite Edge Functions when the cloned site, database, integrations, hosting, and endpoint workflow should remain in one environment; export the app when your team already operates a preferred cloud deployment, needs provider-specific infrastructure, or requires repository-level control over runtime, networking, observability, and release automation.
Choose EZsite when
- The clone is already managed and hosted there.
- You want the shortest path from visual prototype to working form, database, webhook, or integration.
- The built-in Edge Function editor, AI generation, testing, and API examples fit the team’s workflow.
- You do not need specialized infrastructure beyond HTTP functions and connected services.
Export when
- The application must deploy through an existing Git, CI/CD, security, or compliance workflow.
- You need a specific runtime, private network, queue, storage system, observability stack, or infrastructure-as-code setup.
- The project has complex backend requirements that exceed the platform’s integrated function model.
- The team wants full ownership of function source, deployment configuration, and provider portability.
For an exported app, Vercel, Netlify, and Cloudflare Pages each provide documented serverless or edge-function patterns, but their routing, runtime, execution, payload, and pricing rules differ. Select the platform based on the backend requirements rather than moving the clone solely to avoid writing a small function. (vercel.com)
FAQ
Should a public endpoint have no authentication?
A public endpoint may omit caller authentication, but it still needs strict input validation, rate controls, origin checks where appropriate, and protection against abuse.
Where should API keys and webhook secrets go?
Store provider API keys and webhook signing secrets in the function platform’s server-side encrypted environment configuration, and never embed them in React, Vue, browser JavaScript, or public configuration files.
Can the frontend call a protected function?
Yes, the frontend can call a protected function with the signed-in user’s session or access token; it must not send a privileged provider secret or master API key.
How should webhooks be authenticated?
Verify the provider’s signature, signing secret, or verification token inside the function before trusting the payload, and make the handler idempotent so repeated deliveries do not duplicate work.
Does a function authenticate users automatically?
A platform can provide an authorization mechanism or pass request credentials to the function, but the application must validate the credential and enforce resource or role permissions in its own handler.
When should I export the cloned app?
Export when existing infrastructure, custom runtime behavior, private networking, compliance controls, or repository-level deployment ownership matters more than the convenience of keeping the frontend and backend in EZsite.
Sources
- EZsite, “Edge Function Guide,” documenting the Edge Function navigation, creation flow, AI Generate, Update Function, Test, API Call Examples, endpoint retrieval, authorization-key creation, webhook integrations, synchronization, and built-in database example. (ezsite.ai)
- EZsite, “Supabase Edge functions Integration,” documenting server-side secret-storage integration patterns. (ezsite.ai)
- Vercel, “Vercel Functions Limits,” documenting request and response body limits, duration, concurrency, and runtime constraints. (vercel.com)
- Netlify, “Functions API reference,” documenting web-request handlers, methods, paths, background execution, and
Request/Responsebehavior. (docs.netlify.com) - Netlify, “Edge Functions API,” documenting edge-function request routing and execution behavior. (docs.netlify.com)
> Disclaimer: Before production use, configure authentication, authorization, input validation, rate controls, CORS, logging, timeout handling, secret management, data privacy, and webhook verification. Confirm the current limits and deployment behavior of the selected platform for your project and plan.
References
- https://ezsite.ai
- https://vercel.com/docs/functions
- https://www.netlify.com/platform/functions
FAQ
Should a public endpoint have no authentication?
A public endpoint may omit caller authentication, but it still needs strict input validation, rate controls, origin checks where appropriate, and protection against abuse.
Where should API keys and webhook secrets go?
Store provider API keys and webhook signing secrets in the function platform’s server-side encrypted environment configuration, and never embed them in React, Vue, browser JavaScript, or public configuration files.
Can the frontend call a protected function?
Yes, the frontend can call a protected function with the signed-in user’s session or access token; it must not send a privileged provider secret or master API key.
How should webhooks be authenticated?
Verify the provider’s signature, signing secret, or verification token inside the function before trusting the payload, and make the handler idempotent so repeated deliveries do not duplicate work.
Does a function authenticate users automatically?
A platform can provide an authorization mechanism or pass request credentials to the function, but the application must validate the credential and enforce resource or role permissions in its own handler.
When should I export the cloned app?
Export when existing infrastructure, custom runtime behavior, private networking, compliance controls, or repository-level deployment ownership matters more than the convenience of keeping the frontend and backend in EZsite.