Frontend y backend juntos
Conecte la pantalla con el servidor
Frontend y backend juntos es una lección gratuita de Vibe Coding en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Vibe Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Vibe Coding incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Two Halves of One App
Your plan is ready — now let's connect the two halves of a full-stack app. The frontend is everything the user sees and clicks in their browser. The backend is code running on a server that does the heavy lifting: saving data, running logic, talking to a database.
They communicate by sending messages over the internet. In this lesson you'll have AI build both sides and wire them together so a button click on screen actually reaches your server.
How They Talk: Requests and Responses
The frontend and backend talk through HTTP requests. The frontend sends a request ("give me the time entries"); the backend sends back a response (the data, usually as JSON).
You don't need to memorize the details — but knowing this mental model helps you read AI's code and ask better questions when something doesn't connect.
Explain in plain language how a frontend and a backend talk to each other over HTTP.
Use my freelancer hours app as the example: what happens, step by step, when a user clicks 'Add 2 hours for Acme'?
Keep it beginner-friendly and mention the words request, response, and JSON.What Is an API Endpoint?
An API endpoint is a specific URL on your backend that does one job — like /api/entries to list or add time entries. The frontend calls endpoints; the backend answers.
Designing clear endpoints up front keeps your app organized. Ask AI to propose the endpoints your MVP needs based on your features.
For the freelancer hours app, list the API endpoints the MVP needs.
For each endpoint give:
- the method (GET, POST, etc.)
- the path (e.g. /api/entries)
- what it does in one line
- what it returns
Keep it minimal — only endpoints the MVP screens actually call.Generate the Backend Endpoint
Time to build. Ask AI to create one endpoint at a time. Starting small means you can run and test each piece instead of debugging a giant blob.
Notice how the prompt pins the framework and the data shape. The more specific you are, the more the generated code fits the rest of your app.
Using Next.js (App Router) API routes, create a POST endpoint at /api/entries that:
- accepts JSON with { client, hours, date }
- for now, stores entries in an in-memory array (no database yet)
- returns the saved entry as JSON
Also create a GET /api/entries that returns all entries. Add basic input validation and explain the code briefly.Generate the Frontend That Calls It
Now the other half: a screen with a form. When the user submits, the frontend sends the data to your /api/entries endpoint and shows the result.
Tell AI exactly which endpoint to call and what to display. This keeps the two halves in sync.
Build a React component (Next.js page) for adding time entries.
It should:
- show a form with fields: client, hours, date
- on submit, POST the data to /api/entries
- after success, fetch GET /api/entries and list all entries below the form
- show a simple loading and error state
Keep the styling minimal and clean. Explain how the fetch calls connect to my backend.fetch: The Glue Between Them
In the browser, the frontend uses fetch to call your backend. Here's the core pattern AI will generate — a function that sends a new entry and reads the response. Run it to see how a request payload and a parsed response look.
async function addEntry(entry) {
// In a real app this URL hits your backend; here we just simulate it
const fakeServer = (data) => ({ id: 1, ...data, saved: true });
const payload = JSON.stringify(entry);
console.log("Sending to /api/entries:", payload);
const response = fakeServer(JSON.parse(payload));
console.log("Server responded:", response);
return response;
}
addEntry({ client: "Acme", hours: 2, date: "2026-06-10" });Test the Connection End to End
Wiring isn't done until you've watched data flow both ways. Run the app, submit the form, and confirm the new entry appears in the list — that proves the frontend reached the backend and got a response.
If nothing happens, AI is great at diagnosing the gap when you describe exactly what you saw.
I built the form and the /api/entries endpoints. When I submit the form, nothing appears in the list, but I see no error on screen.
Help me debug the connection between frontend and backend. Tell me:
- what to check in the browser's Network tab
- what console.logs to add
- the most common reasons a fetch silently failsSame-Project vs. Separate Servers
You'll hear two setups. In a full-stack framework like Next.js, the frontend and backend live in one project and deploy together — simplest for beginners. Alternatively, you can run a separate backend (its own server) and a separate frontend.
For vibe coding, staying in one project avoids cross-server headaches like CORS. Ask AI which fits your goals.
Compare two setups for my freelancer hours app:
1. One Next.js project containing both frontend and API routes
2. A separate backend server plus a separate frontend
For a beginner who wants to ship fast on Vercel, which do you recommend and why? Mention any extra complexity like CORS that I'd avoid with the simpler option.Handle Errors Gracefully
Real networks fail. A request can time out, the server can return an error, or the data can be malformed. A good app shows the user a friendly message instead of breaking silently.
Ask AI to add error handling to both sides so failures are visible and recoverable.
Add robust error handling to my time-entry feature.
Frontend: if the POST fails, show a friendly inline error and let the user retry.
Backend: validate input and return a clear error message with the right status code (e.g. 400 for bad input).
Show me the updated code and explain what each error case covers.Keep Frontend and Backend in Agreement
The #1 cause of broken full-stack apps is the two halves disagreeing on the data shape — the frontend sends hrs but the backend expects hours.
Keep one source of truth for your data shape (note it in PROJECT.md), and when you change one side, tell the AI to update the other. Consistency is what makes the wiring hold.
I'm changing the time entry shape from { client, hours, date } to { clientId, minutes, date, note }.
Update BOTH the /api/entries endpoint and the frontend form/list to use the new shape consistently. Update PROJECT.md too. Show me a checklist of every place that had to change.You Built a Working Loop
You now have a real round-trip: a user fills a form, the frontend fetches your backend endpoint, the backend processes and responds, and the screen updates. That loop is the heartbeat of every full-stack app.
Right now data only lives in memory and vanishes on restart. Next, we'll make it permanent with a real database.
Quick Check
Make sure the frontend/backend connection is clear.
Recap: Wiring the Two Halves
You connected frontend and backend by prompting AI:
- They communicate via HTTP requests and responses (JSON)
- The backend exposes API endpoints; the frontend calls them with
fetch - Build and test one endpoint at a time
- Add error handling on both sides
- Keep the data shape consistent across frontend and backend
Next: store your data for real with a database so it survives a restart.
Preguntas frecuentes
¿La lección «Frontend y backend juntos» es gratis?
Sí — el texto completo de «Frontend y backend juntos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Vibe Coding, actualiza a CoddyKit PRO. El curso de Vibe Coding incluye 4 lecciones en total.
¿Qué aprenderé en «Frontend y backend juntos»?
Conecte la pantalla con el servidor Practicas Vibe Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Vibe Coding?
No se requiere experiencia previa. Vibe Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «Frontend y backend juntos»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Vibe Coding?
Sí. Cada lección de Vibe Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Planificación de la aplicación con IA
- Frontend y backend juntos
- Cómo añadir una base de datos
- Cuentas de usuario e inicio de sesión