# Why AI-Built Apps Break in Production (And How to Fix It)

> See why apps built with Lovable, Bolt, Cursor, or Replit break in production, and fix env vars, databases, ports, builds, CORS, auth, storage, and crashes.
- **Author**: vamsi-mullapudi
- **Published**: 2026-05-18
- **Modified**: 2026-09-17
- **Category**: Deployment Guides
- **URL**: https://kuberns.com/blogs/why-ai-built-apps-break-in-production/

---

An AI-built app can work locally or in a preview and still break after deployment because production uses a different runtime, network, database, domain and security configuration. The most common causes are missing environment variables, incorrect database connections, hardcoded ports or URLs, build differences, authentication callbacks and non-persistent file storage.

This guide covers web applications created with AI coding and app-building tools such as Lovable, Bolt, Cursor, Replit and Windsurf. It does not cover machine-learning models or AI-agent inference systems failing under production workloads.

Start with the deployment logs and the visible symptom. A build failure, 502 response, database error and broken login require different fixes. The sections below show what to check first, why the problem appears only after deployment and how to correct it without unnecessarily rebuilding the application.

## AI App Works Locally but Not in Production: Check These First

Use this order before changing code at random:

1. **Open the build and runtime logs.** Identify whether the failure happens while installing dependencies, building the app, starting the process or serving a request.
2. **Compare environment variables.** Confirm every required variable exists in production, uses the correct value and is available to the correct build or runtime process.
3. **Verify the database.** Check the production connection string, SSL requirement, network access and whether migrations ran successfully.
4. **Confirm build and start settings.** Make sure the deployment uses the correct package manager, runtime version, build command, output directory and start command.
5. **Check ports and URLs.** The server should use the platform-provided port, and frontend or API URLs must not point to `localhost`.
6. **Review domains and authentication.** Add the production domain to CORS rules and OAuth callback or redirect allowlists.
7. **Check storage and process health.** User uploads need persistent object storage, while the application needs health checks, logs and restart handling.

This sequence separates configuration failures from application bugs and usually reveals the first useful error faster than redeploying unchanged code.

## What Makes AI-Generated Apps Different From Production-Ready Apps

![What makes AI-generated apps different from production-ready apps](https://kuberns-blogs-media.s3.ap-south-1.amazonaws.com/why-ai-generated-apps-different-from-production-ready-apps.png)

AI coding tools and production environments have completely different goals. Understanding that gap is the first step to closing it.

### What AI coding tools are optimised for

Tools like Lovable, Bolt, Cursor, Replit, and Windsurf are optimised for speed. They generate working code fast, wire up components, connect to local databases, and get an app running in development in minutes.

Their main job is generating and editing application code, not guaranteeing that every external production environment is configured correctly. Preview products may provide SSL, databases or secrets inside their own environment, but those settings do not automatically transfer when the application is moved to another host.

### What production environments actually require

A production environment is not your laptop. It is a containerised Linux server with strict resource limits, no filesystem persistence, specific port requirements, enforced HTTPS, and no knowledge of your local environment variables.

Every piece of configuration that exists implicitly on your machine has to be defined explicitly in production. Your database URL, your API keys, your auth secrets, your Node version, your build commands. None of this travels with your code unless you configure it deliberately.

### Why the gap only shows up after deployment

Development environments are forgiving. Your local machine has your secrets in a `.env` file. Your database is running on localhost. Your filesystem is persistent. Your app restarts automatically when it crashes. None of that is true in production by default.

The gap can stay hidden during development because preview environments provide convenient defaults. Production requires explicit, secure settings and exposes the application to real domains, networks, data and traffic. That shift is where many AI-built apps break.

## Why Does an AI-Built App Work Locally But Break in Production

![Why does an AI-built app work locally but break in production](https://kuberns-blogs-media.s3.ap-south-1.amazonaws.com/why-ai-built-app-work-locallyy.png)

This is the most common question developers ask after their first deployment fails, and the answer comes down to environment differences.

### How localhost and cloud environments differ

On localhost, your app connects to a database on `127.0.0.1`. In production, the database is a separate managed service with a different host, a different port, and SSL required. On localhost, your app reads secrets from a `.env` file. In production, that file does not exist unless you explicitly configure environment variables in your deployment platform.

### What changes between development and production

The operating system often changes. AI tools frequently run on macOS or Windows. Production containers run Linux. Native packages like `sharp`, `node-gyp`, and `canvas` compile differently per OS. A package that installs cleanly on your Mac may fail to build on a Linux container.

The runtime version can also differ. If your local machine has Node 20 and the deployment platform defaults to Node 18, packages that depend on newer APIs will break silently.

### Which AI tools are most affected

Tools with managed preview environments can create a larger configuration gap when the app moves to a different provider. Secrets, database integrations and networking behavior used in preview must be recreated or replaced for the target production environment.

Cursor and Windsurf users face a slightly different problem: the code they generate runs locally against a developer-managed environment, but that environment is still not production-grade.

## Environment Variables Are Missing or Incorrectly Set

![Environment variables missing or incorrectly set in production](https://kuberns-blogs-media.s3.ap-south-1.amazonaws.com/environment-variables-missing.png)

Missing or incorrect environment variables are a frequent reason AI-built apps fail after deployment. They can stop database, authentication and third-party integrations from initializing, while exposed or insecurely stored secrets also create a security risk.

### What environment variables does a production app need

At minimum, a production app needs:

- `DATABASE_URL` with the full connection string including host, port, credentials, and SSL parameters
- All third-party API keys (Stripe, SendGrid, Twilio, OpenAI, etc.)
- Auth secrets (JWT secret, NextAuth secret, session secret)
- `NODE_ENV=production`
- Any service URLs your app calls internally

AI tools set these locally in a `.env` file that never leaves your machine. In production, every variable has to be explicitly added to your deployment platform's environment configuration.

### How to check if env vars are causing the crash

Check your deployment logs immediately after the crash. The most common error messages are:

- `Cannot read properties of undefined` means a variable is undefined because the env var is missing
- `ECONNREFUSED` or `connection refused` means the database URL is wrong or missing
- `Invalid API key` means a third-party service key is not set
- `JWT secret not defined` means the auth secret is missing

If the log points to a value that should come from an environment variable, that variable is either not set or set incorrectly.

### How to set environment variables correctly in production

Every deployment platform has an environment variables section in its dashboard. Add each variable from your local `.env` file manually. Never commit your `.env` file to your repository.

If you are moving directly from an AI builder to hosting, follow the complete process for [deploying an AI-built app after vibe coding](https://kuberns.com/blogs/after-vibe-coding-deploy-your-app/) so the required production settings are not missed.

## Database Connection Fails in Production

![Database connection fails in production](https://kuberns-blogs-media.s3.ap-south-1.amazonaws.com/database-connection-fails.png)

Database connection failures are another frequent production issue. The cause may be a missing or incorrect URL, blocked network access, an SSL requirement, unavailable credentials or migrations that were never applied.

### Why AI tools use local or mock databases

AI coding tools default to whatever database is easiest to set up locally. Lovable and Bolt often use Supabase in their preview environments. Cursor-generated apps frequently use SQLite for prototyping. Replit provides its own managed PostgreSQL in preview.

When an app moves to an external deployment, a local database is no longer reachable and a preview integration may not transfer automatically. The production service needs its own reachable database connection and credentials.

### What a production database connection actually needs

A production PostgreSQL connection string looks like this:

```
postgresql://username:password@host:5432/database?sslmode=require
```

Every part of that string has to be correct. The host is not `localhost`. The SSL mode must be set. The credentials must match the production database user, not a local admin account.

If you are migrating from a Supabase preview to a standalone PostgreSQL instance, you also need to run your migrations against the new database before deploying.

### How to fix database connection errors after deployment

Provision a managed database on your deployment platform, copy the connection string it provides, and add it as your `DATABASE_URL` environment variable. Then run your database migrations before traffic hits the app.

> Most developers who struggle with database connections in production are missing one key piece of knowledge. Read [how to deploy a full-stack app correctly from the start](https://kuberns.com/blogs/deploy-full-stack-app-with-ai/).

## CORS, API URLs and Authentication Work in Preview but Fail Live

An application can load successfully while API requests or login flows fail because the production domain was never added to the services it calls.

### Check for localhost and preview URLs

Search the code and production environment variables for `localhost`, `127.0.0.1` and temporary preview domains. Replace them with the production frontend or API URL where appropriate. Keep client-visible variables separate from server-only secrets according to the framework's environment-variable rules.

### Add the production origin to CORS

If the browser reports a CORS error, allow the exact production origin on the API. Do not solve the problem by allowing every origin when requests carry credentials. Confirm that the frontend uses the correct HTTPS API URL and that preflight `OPTIONS` requests reach the backend.

### Update OAuth callback and redirect URLs

Google, GitHub, Discord and other identity providers only redirect to approved URLs. Add the live callback URL in the provider dashboard and update the application's base URL or authentication URL. Also review cookie settings: production sessions commonly require HTTPS, a secure cookie and the correct domain or same-site policy.

## App Crashes Because of Wrong Port Configuration

![App crashes because of wrong port configuration](https://kuberns-blogs-media.s3.ap-south-1.amazonaws.com/app-crash-because-of-wrong-port-config.png)

Port misconfiguration is one of the quietest failures in production deployment. The app appears to deploy successfully but is completely unreachable.

### What port does a production app need to listen on

Most cloud platforms route external traffic through port 80 (HTTP) and 443 (HTTPS) and then forward it internally to whatever port your app is listening on. The platform detects this automatically if your app reads the port from the `PORT` environment variable.

The problem is that AI-generated apps often hardcode the port. `app.listen(3000)` works perfectly on localhost. In a container environment, the platform sets `PORT` to a dynamic value and expects your app to use it. If your app ignores `PORT` and listens on 3000, the platform cannot route traffic to it and the app appears to be down.

### Why container platforms reject the wrong port silently

Container platforms do not always produce a clear error when the port is wrong. The deployment succeeds, the container starts, but requests time out or return a 502. The app is running but unreachable because nothing is listening on the expected port.

### How to fix port configuration without touching your app logic

Change your app's listen call to use the `PORT` environment variable with a local fallback:

```js
const port = process.env.PORT || 3000;
app.listen(port);
```

This pattern works on platforms that expose the assigned internal port through the `PORT` environment variable. Confirm the expected binding in the provider's documentation and make sure the server listens on the required network interface.

## HTTPS Not Working After Deployment

Every production app needs HTTPS. Without it, browsers flag your app as insecure, payment providers refuse to work, and auth flows break.

### Why does my deployed app not have HTTPS

HTTPS requires an SSL certificate issued for your domain. Certificates are not automatic unless your deployment platform provisions them for you. On most manual setups, you have to configure a reverse proxy like Nginx, install Certbot, and renew the certificate every 90 days.

SSL provisioning belongs to the hosting and domain layer rather than the generated application code. Some managed platforms configure it automatically after the domain is connected, while a manually managed server requires certificate and reverse-proxy configuration.

### What breaks when SSL is not configured

Without HTTPS:

- Google Chrome marks your app as "Not Secure"
- Stripe, Google OAuth, and most third-party auth providers refuse to work
- Browser security policies block mixed-content requests
- Users on corporate networks may be blocked entirely

### How to get a free SSL certificate for your deployed app

On a VPS, use Certbot with Let's Encrypt. On managed platforms, SSL is typically handled automatically when you connect a custom domain. The key is choosing a platform that handles this for you rather than adding it to your own configuration list.

> Not sure what a deployment platform actually handles vs what you have to do yourself? [Here is the complete breakdown of what one-click deployment does](https://kuberns.com/blogs/what-does-one-click-deployment-do/).

## Build Passes Locally But Fails on the Deployment Server

A build that passes locally but fails in production is one of the most confusing deployment errors because there is no obvious change between the two environments.

### Why does my app build fail in production but not locally

The most common cause is a platform-specific native dependency. Packages like `sharp` (image processing), `canvas`, `node-gyp`, and `bcrypt` compile native binaries during installation. On macOS, they compile for macOS. On the Linux container your deployment uses, they need to recompile for Linux.

If your `node_modules` folder is committed to your repository or cached incorrectly, the macOS binaries are used in the Linux container and the build fails.

### Common packages that break on Linux containers

- `sharp` requires libvips, often not available in minimal containers
- `node-gyp` requires Python and build tools
- `canvas` requires Cairo and other native graphics libraries
- `bcrypt` sometimes needs to recompile on the target architecture

### How to make your build consistent across environments

Do not commit `node_modules` to your repository. Let the deployment platform run `npm install` or `yarn install` fresh on every deploy. Specify your Node version explicitly in a `.nvmrc` file or in your `package.json` engines field. This ensures the build environment matches what your app expects.

> Build failures are just one pattern in a longer list of avoidable deployment problems. See every common failure mode explained: [Why Do Software Deployments Fail](https://kuberns.com/blogs/why-do-software-deployments-fail/).

## Static Files and Images Break After Going Live

Working images and CSS in development that disappear after deployment is a container filesystem problem, not a code problem.

### Why do images and CSS stop working after deployment

On your local machine, static files are served directly from the filesystem. A path like `./public/images/logo.png` resolves correctly because the file exists relative to where your app is running.

In a container, the working directory may differ. More importantly, containers do not have persistent filesystems by default. Any file that was not included in the build does not exist at runtime. User-uploaded files disappear on every redeploy.

### How file paths differ between local and production

Relative filesystem paths that work locally often break in containers because the working directory is different. For user-generated uploads, the file is written to the container filesystem, survives until the container restarts, and then disappears. Any upload feature that works locally will silently lose data in production unless you configure external storage.

### How to serve static assets correctly in production

For static build assets bundled at build time, your framework's build process handles this correctly as long as you run the build step before deployment. Ensure your deployment platform runs `npm run build` and serves the output directory.

For user uploads, replace filesystem storage with an object storage service. Write uploads to S3 or Cloudflare R2 and store the URL in your database rather than the file itself.

## App Goes Down After the First Real Traffic Spike

An app that works fine for one user but crashes under real traffic is a reliability problem that AI tools never address during code generation.

### Why does my app crash under load

AI-generated apps are built for functionality, not scale. A Node.js app running as a single process with no memory management will consume all available memory under moderate traffic and crash. Without a process manager, it stays down until manually restarted.

Health monitoring, restart behavior and recovery planning help prevent a single process failure from becoming prolonged downtime. Microsoft's [reliability design guidance](https://learn.microsoft.com/en-us/azure/architecture/framework/resiliency/app-design) recommends designing applications to detect failures and recover from them.

Common causes of crash-under-load:

- Unhandled promise rejections that terminate the process
- Memory leaks that accumulate until the container hits its limit
- Database connection pool exhaustion when concurrent users exceed the pool size
- Synchronous operations blocking the event loop under concurrent requests

### What is a process manager and why does your app need one

A process manager like PM2 keeps your app running by automatically restarting it when it crashes. It also allows you to run multiple instances of your app on the same server to handle more concurrent requests.

Without a process manager, a single crash means your app is down until you manually restart it. For a production app serving real users, that is not acceptable.

### How to configure auto-restart and basic scaling

On a VPS, a process manager or operating-system service can restart the application after a crash. If using PM2, configure and test both process restart and startup after a server reboot rather than assuming the default command covers both cases.

On managed platforms, auto-restart is handled by the platform's container orchestration layer. The key setting to check is whether your platform restarts containers on failure.

> Solo founders who skip the reliability setup pay for it later. See why it matters from day one: [How to Deploy a SaaS App in 2026](https://kuberns.com/blogs/how-to-deploy-a-saas-app/).

## Why Later AI Edits Can Break Features That Already Worked

AI coding tools can change shared components, data models, dependencies or environment assumptions while implementing a new request. A feature may look correct in the preview even though another route or production integration has regressed.

Reduce this risk by keeping generated changes small and reviewable. Commit a working version before each substantial prompt, use a lockfile, run the production build locally or in CI, and test the critical paths such as signup, login, payments, database writes and file uploads. Preview deployments are useful for checking each change against production-like configuration before it reaches users.

If a release fails, compare it with the last working commit instead of asking the AI tool to rewrite unrelated parts of the app. A rollback restores service while logs and the code diff identify the actual regression.

## How to Fix AI App Production Issues Without Rebuilding the App

![How to fix AI app production issues without rewriting your code](https://kuberns-blogs-media.s3.ap-south-1.amazonaws.com/how-to-fix-ai-app-production-issues.png)

Many failures above can be fixed through deployment configuration, but some require a focused code change, such as reading the assigned port, removing a hardcoded URL or correcting cookie behavior. Diagnose the failing layer first so a small configuration or code fix does not become an unnecessary rewrite.

### Which production issues are fixable without a DevOps engineer

Use this fix list as a starting point:

- Missing env vars: add them in your deployment platform dashboard
- Wrong database: provision a managed DB and update the connection string
- Port issue: read the platform-provided port and bind to the required interface
- No HTTPS: use a platform that provisions SSL automatically
- Build failures: clear the module cache and let the platform reinstall fresh
- CORS or login failure: allow the production origin and update OAuth callback URLs
- Static files: configure your build output directory correctly
- Crashes under load: use a platform with auto-restart enabled

The time required depends on the error, the application architecture and whether production logs expose the root cause. Fix and verify one failure at a time.

### What to look for in a deployment platform for AI-built apps

A deployment platform built for AI-generated apps should handle the entire infrastructure layer so you do not have to think about it:

- Automatic SSL provisioning on every custom domain
- Automatic port detection without hardcoding
- Built-in environment variable management
- Managed database provisioning with the connection string pre-configured
- Auto-restart on crash with no manual intervention
- GitHub integration with automatic redeploy on push

### Why manual platforms make this harder than it needs to be

Platforms that require manual server configuration put the entire infrastructure burden on you. Setting up Nginx, configuring Certbot, managing PM2, provisioning a database, setting security groups. This is full-time DevOps work that has nothing to do with the app you built.

> Choosing the right platform is the most important decision you make after finishing your app. Here is how developers are [deploying full-stack SaaS apps without a DevOps team](https://kuberns.com/blogs/how-to-deploy-a-saas-app/).

## How Kuberns Removes the Manual Deployment Layer

![Deploy your AI-built app the right way with Kuberns](https://kuberns-blogs-media.s3.ap-south-1.amazonaws.com/kuberns-home-page-new.png)

The troubleshooting steps above show why deploying an AI-built app involves more than uploading generated code. The host still needs to identify the framework, build the correct output, run the right process, route traffic and provide the production services the application expects.

Kuberns is an agentic AI platform for deployment that analyzes a connected repository and prepares the application environment. Instead of asking the developer to write infrastructure configuration, it handles the deployment setup while the developer supplies the secure environment variables required by the application.

### How Kuberns handles production configuration automatically

For a supported application, Kuberns handles the following deployment work:

- Analyzing the repository and detecting the framework, runtime and dependencies
- Preparing the build and runtime configuration
- Handling application networking, HTTPS and custom-domain deployment
- Providing logs and deployment status for troubleshooting
- Supporting Git-based deployments and subsequent releases
- Provisioning supported application resources through the platform workflow

The developer's required step is to provide the application's secure environment variables, such as API keys, authentication secrets and external service credentials. Those values should be reviewed rather than guessed or committed to the repository.

### Deploy in three steps

1. Connect your GitHub repository to Kuberns
2. Add your environment variables in the Kuberns dashboard
3. Click deploy

After deployment, verify the live URL, logs, database-dependent workflows, authentication and other critical paths before directing production traffic to the application.

## Conclusion

When an AI-built app works locally but fails in production, start with the first failing stage rather than rewriting the project. Check the logs, environment variables, database, build and start commands, ports, production URLs, CORS rules, authentication callbacks and persistent storage in that order.

Kuberns is the practical choice for developers who want to deploy an AI-built application without manually configuring the infrastructure layer. Its agentic AI analyzes the repository and prepares the deployment environment, while the developer only needs to provide secure application environment variables and verify the live workflows.

[Deploy your AI-built application on Kuberns](https://dashboard.kuberns.com)

<a href="https://dashboard.kuberns.com" target="_blank" rel="noopener noreferrer">
  <img src="https://kuberns-blogs-media.s3.ap-south-1.amazonaws.com/CTA_banner.png" alt="Deploy your AI-built application on Kuberns" style={{ width: "100%", height: "auto" }} />
</a>

## Frequently Asked Questions

**Why does my Lovable app work in preview but break when deployed?**

Lovable preview environments inject environment variables and database connections automatically. When you deploy to an external platform, those values are missing unless you set them manually. Configure all env vars and database connection strings in your deployment platform.

**Why is my Bolt app showing a 502 error in production?**

A 502 error means the app is either not running, listening on the wrong port, or crashing on startup due to a missing environment variable or failed database connection. Check your startup logs first and confirm your app reads the port from `process.env.PORT`.

**Why does my Replit app crash after going live?**

Replit apps rely on Replit-managed secrets and a persistent process that external platforms do not replicate automatically. Migrate your secrets to the target platform's environment settings and confirm auto-restart is active.

**How do I fix environment variable errors in a deployed app?**

Go to your deployment platform's environment settings and add every variable your app references. Common ones include `DATABASE_URL`, API keys, JWT secrets, and third-party service credentials. Never hardcode these values in your code.

**Why is my AI-built app not connecting to the database in production?**

AI tools use local SQLite or mock databases during development. In production you need a managed database with the correct connection string including host, port, username, password, and SSL mode set as an environment variable.

**Does Kuberns fix deployment issues automatically?**

Kuberns uses agentic AI to analyze the connected repository and prepare the deployment environment, including the build and runtime setup. The developer provides the application's secure environment variables and verifies the live workflows after deployment.

---
- [More Deployment Guides articles](https://kuberns.com/blogs/category/deployment-guides/1/)
- [All articles](https://kuberns.com/blogs/)