Build an AI Code Generation Feature in a Browser Playground
In this article
This guide walks you through creating a browser-based playground where users can type a prompt and receive generated code from an AI model. You'll build a simple front-end interface, connect it to an AI API (like OpenAI or Anthropic), and handle streaming responses for a smooth user experience. By the end, you'll have a functional tool you can extend with syntax highlighting, multiple language support, and more.
What You'll Need
- Basic knowledge of HTML, CSS, and JavaScript (ES6+).
- A code editor (VS Code, Sublime, etc.).
- A modern web browser (Chrome, Firefox, Edge).
- An API key from an AI provider that supports code generation (e.g., OpenAI, Anthropic, or a local model via Ollama).
- Node.js installed if you plan to use a backend proxy to keep your API key secure.
Step-by-Step
- Set up the project structure. Create a folder named
ai-playground. Inside, create three files:index.html,style.css, andscript.js. For simplicity, we'll run this directly in the browser without a build step. - Build the HTML layout. In
index.html, create a textarea for the prompt, a button to trigger generation, and a pre or code block to display the output. Add a language selector (e.g., Python, JavaScript) as a dropdown. Structure it like this:<div class="container"> <h1>AI Code Generator</h1> <select id="language"> <option value="python">Python</option> <option value="javascript">JavaScript</option> </select> <textarea id="prompt" placeholder="Describe the code you need..."></textarea> <button id="generate">Generate Code</button> <pre id="output"></pre> </div> - Style the interface. In
style.css, add basic styling: a centered container, responsive textarea, and a monospace font for the output. Keep it clean and minimal. Example:body { font-family: Arial, sans-serif; background: #f4f4f4; } .container { max-width: 700px; margin: 50px auto; padding: 20px; background: white; border-radius: 8px; } textarea { width: 100%; height: 150px; margin: 10px 0; font-family: monospace; } #output { background: #1e1e1e; color: #d4d4d4; padding: 15px; border-radius: 4px; overflow-x: auto; } - Handle the button click. In
script.js, add an event listener to the button. On click, get the prompt and language values, then call a functiongenerateCode()that will make the API request. - Set up the AI API call. You have two options:
- Direct from browser (not recommended for production): Use the provider's JavaScript SDK or fetch to their API endpoint. You'll expose your API key in the client, which is a security risk.
- Via a backend proxy (recommended): Create a small Node.js server that holds your API key and forwards requests. This keeps the key secret. For this guide, we'll use a simple backend with Express.
- Create the backend proxy. If using Node.js, create a
server.jsfile. Install Express and the AI SDK (e.g.,openai). Set up a POST endpoint/generatethat receives the prompt and language, calls the AI model, and returns the code. Example:const express = require('express'); const OpenAI = require('openai'); const app = express(); app.use(express.json()); const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); app.post('/generate', async (req, res) => { const { prompt, language } = req.body; const response = await openai.chat.completions.create({ model: 'gpt-3.5-turbo', messages: [{ role: 'user', content: `Write ${language} code: ${prompt}` }] }); res.json({ code: response.choices[0].message.content }); }); app.listen(3000, () => console.log('Server running on port 3000')); - Connect the frontend to the backend. In
script.js, usefetchto POST tohttp://localhost:3000/generatewith the prompt and language. Update the output element with the returned code. Example:async function generateCode() { const prompt = document.getElementById('prompt').value; const language = document.getElementById('language').value; const response = await fetch('http://localhost:3000/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt, language }) }); const data = await response.json(); document.getElementById('output').textContent = data.code; } - Add loading state and error handling. Disable the button and show a "Generating..." message while waiting. Wrap the fetch in a try/catch block to display errors if the request fails.
- Test locally. Start the backend with
node server.js, then openindex.htmlin your browser. Enter a prompt like "Write a function that checks if a number is prime" and click Generate. You should see the code appear. - Enhance with streaming (optional). For a more interactive feel, use the API's streaming capabilities. In the backend, set
stream: trueand send chunks via Server-Sent Events or WebSockets. This is more advanced but improves perceived speed.
Common Mistakes
- Exposing your API key in the frontend. Anyone can steal it and rack up charges. Always use a backend proxy.
- Not handling CORS. If your frontend and backend are on different ports, you'll need to enable CORS in the backend. Add
const cors = require('cors'); app.use(cors());. - Ignoring the model's token limit. Long prompts or expected long code outputs can exceed the model's max tokens. Set a reasonable
max_tokensparameter and handle truncation. - Forgetting to sanitize user input. While the AI handles most text, always escape HTML in the output to prevent XSS attacks when using
innerHTML. UsetextContentas shown.
Tips
- Use a system prompt to instruct the model to output only code, no explanations. For example: "You are a code generator. Output only the code, no markdown."
- Add a "Copy" button to let users copy the generated code easily.
- Implement syntax highlighting using a library like Prism.js or highlight.js for better readability.
- Allow users to choose the model (e.g., GPT-3.5 vs GPT-4) if your provider supports multiple models.
- Cache common requests to reduce API costs and improve response time.
Troubleshooting
- No response or blank output: Check the browser's console (F12) for errors. Verify the backend is running and the endpoint URL is correct. Test the API directly with a tool like Postman.
- CORS errors: If you see "No 'Access-Control-Allow-Origin' header", install the
corspackage in your backend and use it as shown above. - API key not working: Ensure the key is correctly set as an environment variable. Double-check for extra spaces or quotes. Try a simple curl request to the provider's API.
- Generated code is truncated: Increase the
max_tokensparameter in your API call. Be aware of the model's context window limits. - Output contains markdown or explanations: Adjust the system prompt to explicitly request only raw code. For example: "Return only the code, no backticks or comments."
Frequently Asked Questions
Can I use a free AI API?
Yes, some providers offer free tiers or trial credits. For example, OpenAI gives a limited amount of free credits for new users. Alternatively, you can run a local model like CodeLlama via Ollama, which is free and private.
Do I need a backend at all?
For a production app, yes, to protect your API key. For a personal project or demo, you can call the API directly from the browser, but be aware of the security risk. If you do, use environment variables in a build tool, but they can still be exposed.
How do I add support for more languages?
Simply add more options to the dropdown and pass the language name to the prompt. The AI model understands language names, so no extra logic is needed.
What if the generated code has errors?
You can add a "Run" button that sends the code to a sandboxed execution environment (like a Web Worker or an iframe with sandbox attribute) to test it. This is complex but possible.
Can I use this for non-code text generation?
Yes, just change the prompt to ask for text instead of code. The same architecture works for any text generation task.
How do I deploy this online?
Deploy the backend to a service like Heroku, Render, or Vercel (with serverless functions). Host the frontend on Netlify or GitHub Pages. Ensure the backend URL is updated in your frontend code.