Replit - complete guide to the cloud IDE with AI
What is Replit?
Replit is a complete cloud development environment that lets you write, run, and deploy code directly in the browser - without any local installation. It supports over 50 programming languages and offers advanced AI features, including Replit Agent, which can autonomously build applications from text descriptions.
Replit is revolutionizing the way people learn programming and build projects. Thanks to instant access to a fully configured environment, anyone can start coding in seconds, regardless of their hardware or operating system.
Why Replit?
Key advantages
- Zero configuration - Environment ready instantly, no installation needed
- 50+ languages - Python, JavaScript, Go, Rust, Java, C++, and more
- Replit Agent - AI builds apps from prompts
- Ghostwriter - Intelligent code suggestions
- Multiplayer - Real-time coding with others
- Instant Deploy - One click to production
- Education - Perfect for learning and teaching
Replit vs the competition
| Feature | Replit | CodeSandbox | StackBlitz | GitHub Codespaces |
|---|---|---|---|---|
| Languages | 50+ | Web focus | Web focus | All |
| AI Agent | Replit Agent | No | Bolt.new | Copilot |
| Deploy | Built-in | Partial | Netlify | External |
| Multiplayer | Yes | Yes | No | Live Share |
| Databases | Built-in | No | SQLite | External |
| Price (Pro) | $20/month | $12/month | $20/month | $19/month |
| Education | Teams for Education | No | No | GitHub Education |
Replit basics
Creating a Repl
A Repl (short for "Read-Eval-Print Loop") is a single project in Replit:
// Creating a new Repl:
1. Click "+ Create Repl"
2. Choose a language/template:
- Python
- Node.js
- React
- Next.js
- Flask
- Django
- Express
- Go
- Rust
- ... and 40+ others
3. Name your project
4. Click "Create Repl"
// The environment starts automatically!Project structure
my-project/
├── .replit # Replit configuration
├── replit.nix # Nix environment config
├── main.py # Main file (or main.js, etc.)
├── requirements.txt # Python dependencies
├── package.json # Node.js dependencies
└── ... your files ....replit configuration
# .replit - project configuration
run = "python main.py"
entrypoint = "main.py"
language = "python3"
[nix]
channel = "stable-23_05"
[env]
PYTHONPATH = "${PYTHONPATH}:${REPL_HOME}"
[deployment]
run = ["sh", "-c", "python main.py"]
deploymentTarget = "cloudrun"
[[ports]]
localPort = 8080
externalPort = 80Nix environment
Replit uses Nix to manage dependencies:
# replit.nix
{ pkgs }: {
deps = [
pkgs.python310
pkgs.python310Packages.pip
pkgs.python310Packages.flask
pkgs.nodejs-18_x
pkgs.postgresql
pkgs.redis
];
env = {
PYTHONPATH = "${pkgs.python310Packages.flask}/lib/python3.10/site-packages";
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath [
pkgs.stdenv.cc.cc.lib
]}";
};
}Replit Agent
Replit Agent is an autonomous AI assistant that can build complete applications from text descriptions.
Replit Agent capabilities
// What Agent can do:
1. CREATE A PROJECT
"Build a todo app with React and Express"
→ Agent creates the structure, installs dependencies, writes code
2. CONFIGURE A BACKEND
"Set up a PostgreSQL database with user authentication"
→ Agent configures the database, creates tables, implements auth
3. DEBUG
"Fix the bug where tasks don't save to the database"
→ Agent analyzes the code, identifies the problem, fixes it
4. REFACTOR
"Refactor the API to use proper error handling"
→ Agent rewrites the code following best practices
5. DEPLOY
"Deploy this app with HTTPS and a custom domain"
→ Agent configures the deploymentExample session with Agent
// App building session
You: Build a blog platform with:
- User registration and login
- Create, edit, delete posts
- Categories and tags
- Comment system
- Admin dashboard
Use Python Flask with SQLite.
Agent: I'll build this blog platform for you. Let me start by:
1. Setting up the Flask project structure
2. Creating the database models
3. Implementing user authentication
4. Building the blog post CRUD
5. Adding comments functionality
6. Creating the admin dashboard
[Agent creates files...]
/main.py
/models.py
/routes/
auth.py
posts.py
comments.py
admin.py
/templates/
base.html
index.html
post.html
login.html
register.html
admin/
dashboard.html
posts.html
/static/
style.css
/requirements.txt
Agent: I've created the basic structure. Let me now implement
the user authentication system...
[Agent writes authentication code...]
Agent: User auth is ready. Now implementing the blog posts...
[Agent continues building...]
Agent: The blog platform is ready! Here's what I've built:
✅ User registration and login with Flask-Login
✅ Blog posts with CRUD operations
✅ Categories and tags system
✅ Comment system with replies
✅ Admin dashboard with analytics
You can test it by clicking the "Run" button.
Would you like me to add any additional features?Effective prompts for Agent
// ✅ Good prompts
"Build an e-commerce API with Node.js and Express.
Include:
- Product catalog with categories
- User accounts
- Shopping cart
- Order processing
Use MongoDB for the database."
"Create a real-time chat application using Python Flask
and Socket.IO. Support multiple chat rooms, private messages,
and typing indicators. Store messages in SQLite."
"Build a REST API for a task management app.
Include:
- JWT authentication
- Tasks with priorities and due dates
- Projects to organize tasks
- Tags system
Use PostgreSQL and include API documentation."
// ❌ Weak prompts
"Make me an app" // Too vague
"Build Twitter clone" // Too ambitious
"Write some code" // No contextGhostwriter - AI code completion
Ghostwriter is a built-in AI assistant that offers intelligent real-time code suggestions.
Ghostwriter features
# 1. COMPLETE CODE - Auto-completion
def calculate_total(items):
# Ghostwriter suggests:
total = 0
for item in items:
total += item.price * item.quantity
return total
# 2. GENERATE CODE - Generation from comments
# Function to validate email address using regex
def validate_email(email):
# Ghostwriter generates the implementation:
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
# 3. EXPLAIN CODE - Explanations
# Select code and click "Explain" - Ghostwriter will explain what it does
# 4. TRANSFORM CODE - Transformations
# Ghostwriter can:
# - Add type hints
# - Convert to async
# - Add error handling
# - RefactorGhostwriter Chat
// Interactive AI chat in the IDE
You: How do I connect to PostgreSQL in this Flask app?
Ghostwriter: Here's how to set up PostgreSQL with Flask:
1. First, install the required packages:
```python
# requirements.txt
psycopg2-binary==2.9.9
Flask-SQLAlchemy==3.1.1- Configure the database connection:
# config.py
import os
class Config:
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'postgresql://user:password@localhost/dbname'
SQLALCHEMY_TRACK_MODIFICATIONS = False- Initialize SQLAlchemy:
# app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config.Config')
db = SQLAlchemy(app)Would you like me to add this to your project?
You: Yes, add it
Ghostwriter: Done! I've added the configuration. You can now create your models.
## Multiplayer coding
Replit allows real-time coding with other people - like Google Docs for code.
### Multiplayer features// INVITING COLLABORATORS
- Click "Invite" in the top right corner
- Enter a username or email
- Choose permissions:
- Can edit - full editing access
- Can view - read only
// REAL-TIME EDITING
- You can see all participants' cursors
- Each person has a different color
- Changes are visible instantly
- Chat built into the IDE
// LIVE SESSIONS
- Collaborative debugging
- Pair programming
- Real-time code review
- Learning to code together
### Multiplayer use cases// 1. PAIR PROGRAMMING Two developers working on the same code:
- Driver writes code
- Navigator suggests and reviews
- Role switching by taking over the cursor
// 2. CODE INTERVIEW Conducting technical interviews:
- Candidate writes code
- Interviewer watches live
- Ability to ask questions in chat
- Session recording
// 3. EDUCATION Teacher with a group of students:
- Live demonstrations
- Students can follow along
- Collaborative problem solving
- Individual assistance
## Databases in Replit
### Replit Database (Key-Value)
```python
# Built-in simple key-value database
from replit import db
# Saving
db["user_123"] = {"name": "Jan", "email": "jan@example.com"}
db["count"] = 42
# Reading
user = db["user_123"]
print(user["name"]) # "Jan"
# Checking a key
if "user_123" in db:
print("User exists")
# Deleting
del db["user_123"]
# Iterating over keys
for key in db.keys():
print(f"{key}: {db[key]}")
# Prefixes
user_keys = db.prefix("user_")
for key in user_keys:
print(db[key])PostgreSQL
# PostgreSQL configuration in Replit
# 1. Add PostgreSQL in replit.nix:
# deps = [ pkgs.postgresql ];
# 2. Set environment variables in Secrets:
# DATABASE_URL = postgresql://...
# 3. Use in code:
import os
import psycopg2
from psycopg2.extras import RealDictCursor
def get_db():
return psycopg2.connect(
os.environ['DATABASE_URL'],
cursor_factory=RealDictCursor
)
# Usage example
def get_users():
conn = get_db()
cur = conn.cursor()
cur.execute("SELECT * FROM users")
users = cur.fetchall()
cur.close()
conn.close()
return users
def create_user(name, email):
conn = get_db()
cur = conn.cursor()
cur.execute(
"INSERT INTO users (name, email) VALUES (%s, %s) RETURNING id",
(name, email)
)
user_id = cur.fetchone()['id']
conn.commit()
cur.close()
conn.close()
return user_idSQLite
# SQLite - the simplest option for small projects
import sqlite3
from contextlib import contextmanager
DATABASE = 'app.db'
@contextmanager
def get_db():
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
try:
yield conn
finally:
conn.close()
def init_db():
with get_db() as conn:
conn.execute('''
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
completed BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
conn.commit()
def get_tasks():
with get_db() as conn:
cursor = conn.execute('SELECT * FROM tasks ORDER BY created_at DESC')
return [dict(row) for row in cursor.fetchall()]
def create_task(title):
with get_db() as conn:
cursor = conn.execute(
'INSERT INTO tasks (title) VALUES (?)',
(title,)
)
conn.commit()
return cursor.lastrowidDeploy and hosting
Replit Deployments
// DEPLOYMENT TYPES
1. AUTOSCALE
- Scales automatically with traffic
- You pay for actual usage
- Ideal for production applications
- Cold starts may occur
2. RESERVED VM
- Dedicated virtual machine
- Fixed resources (CPU, RAM)
- Always on
- Predictable costs
3. STATIC
- For static sites
- Hosting HTML/CSS/JS files
- CDN included
- Cheapest optionDeployment configuration
# .replit - deployment config
[deployment]
run = ["sh", "-c", "python main.py"]
deploymentTarget = "cloudrun"
ignorePorts = false
# Or for Node.js:
[deployment]
run = ["sh", "-c", "npm start"]
build = ["sh", "-c", "npm run build"]
deploymentTarget = "cloudrun"Custom domains
// Adding your own domain:
1. In the deployment panel → "Custom Domains"
2. Enter your domain (e.g. myapp.com)
3. Add DNS records:
- CNAME: myapp.com → your-repl.replit.app
- or A record for apex domain
4. Wait for DNS propagation
5. SSL certificate is generated automaticallyEnvironment Variables (Secrets)
# Storing sensitive data
# 1. In the Tools panel → Secrets
# 2. Add key-value pairs:
# API_KEY = your-secret-key
# DATABASE_URL = postgresql://...
# 3. Use in code:
import os
api_key = os.environ['API_KEY']
db_url = os.environ['DATABASE_URL']
# IMPORTANT: Never commit secrets to your code!Practical projects
Web API with Flask
# main.py - REST API
from flask import Flask, jsonify, request
from flask_cors import CORS
import os
app = Flask(__name__)
CORS(app)
# In-memory storage (use DB in production)
tasks = []
task_id_counter = 1
@app.route('/api/tasks', methods=['GET'])
def get_tasks():
return jsonify(tasks)
@app.route('/api/tasks', methods=['POST'])
def create_task():
global task_id_counter
data = request.json
task = {
'id': task_id_counter,
'title': data['title'],
'completed': False
}
task_id_counter += 1
tasks.append(task)
return jsonify(task), 201
@app.route('/api/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
data = request.json
for task in tasks:
if task['id'] == task_id:
task.update(data)
return jsonify(task)
return jsonify({'error': 'Task not found'}), 404
@app.route('/api/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
global tasks
tasks = [t for t in tasks if t['id'] != task_id]
return '', 204
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)Full-stack app with React + Express
// server/index.js
const express = require('express');
const cors = require('cors');
const path = require('path');
const app = express();
app.use(cors());
app.use(express.json());
// Serve static files from React build
app.use(express.static(path.join(__dirname, '../client/build')));
// API routes
let todos = [];
let idCounter = 1;
app.get('/api/todos', (req, res) => {
res.json(todos);
});
app.post('/api/todos', (req, res) => {
const todo = {
id: idCounter++,
text: req.body.text,
completed: false,
createdAt: new Date().toISOString()
};
todos.push(todo);
res.status(201).json(todo);
});
app.patch('/api/todos/:id', (req, res) => {
const todo = todos.find(t => t.id === parseInt(req.params.id));
if (!todo) return res.status(404).json({ error: 'Not found' });
Object.assign(todo, req.body);
res.json(todo);
});
app.delete('/api/todos/:id', (req, res) => {
todos = todos.filter(t => t.id !== parseInt(req.params.id));
res.status(204).send();
});
// Handle React routing
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../client/build/index.html'));
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on port ${PORT}`);
});// client/src/App.jsx
import { useState, useEffect } from 'react';
import './App.css';
function App() {
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState('');
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchTodos();
}, []);
const fetchTodos = async () => {
const res = await fetch('/api/todos');
const data = await res.json();
setTodos(data);
setLoading(false);
};
const addTodo = async (e) => {
e.preventDefault();
if (!newTodo.trim()) return;
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: newTodo })
});
const todo = await res.json();
setTodos([...todos, todo]);
setNewTodo('');
};
const toggleTodo = async (id) => {
const todo = todos.find(t => t.id === id);
const res = await fetch(`/api/todos/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ completed: !todo.completed })
});
const updated = await res.json();
setTodos(todos.map(t => t.id === id ? updated : t));
};
const deleteTodo = async (id) => {
await fetch(`/api/todos/${id}`, { method: 'DELETE' });
setTodos(todos.filter(t => t.id !== id));
};
if (loading) return <div className="loading">Loading...</div>;
return (
<div className="app">
<h1>Todo App</h1>
<form onSubmit={addTodo} className="add-form">
<input
type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
placeholder="Add a new task..."
/>
<button type="submit">Add</button>
</form>
<ul className="todo-list">
{todos.map(todo => (
<li key={todo.id} className={todo.completed ? 'completed' : ''}>
<span onClick={() => toggleTodo(todo.id)}>
{todo.text}
</span>
<button onClick={() => deleteTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
<p className="count">
{todos.filter(t => !t.completed).length} tasks remaining
</p>
</div>
);
}
export default App;Discord Bot
# main.py - Discord bot
import discord
from discord.ext import commands
import os
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user} is now running!')
@bot.command(name='hello')
async def hello(ctx):
await ctx.send(f'Hello, {ctx.author.name}! 👋')
@bot.command(name='ping')
async def ping(ctx):
latency = round(bot.latency * 1000)
await ctx.send(f'Pong! Latency: {latency}ms')
@bot.command(name='poll')
async def poll(ctx, *, question):
embed = discord.Embed(
title='📊 Poll',
description=question,
color=discord.Color.blue()
)
message = await ctx.send(embed=embed)
await message.add_reaction('👍')
await message.add_reaction('👎')
@bot.command(name='clear')
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount: int = 5):
await ctx.channel.purge(limit=amount + 1)
await ctx.send(f'Cleared {amount} messages! 🧹', delete_after=3)
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('You do not have permission to use this command.')
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f'Missing argument: {error.param.name}')
# Keep bot alive (for Replit)
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return 'Bot is running!'
def run():
app.run(host='0.0.0.0', port=8080)
Thread(target=run).start()
# Run bot
bot.run(os.environ['DISCORD_TOKEN'])Machine Learning API
# main.py - ML prediction API
from flask import Flask, jsonify, request
import numpy as np
from sklearn.linear_model import LinearRegression
import joblib
import os
app = Flask(__name__)
# Train a simple model (in production, load pre-trained)
def train_model():
# Example: predict house price based on size
X = np.array([[1000], [1500], [2000], [2500], [3000]])
y = np.array([150000, 200000, 250000, 300000, 350000])
model = LinearRegression()
model.fit(X, y)
joblib.dump(model, 'model.pkl')
return model
# Load or train model
if os.path.exists('model.pkl'):
model = joblib.load('model.pkl')
else:
model = train_model()
@app.route('/api/predict', methods=['POST'])
def predict():
data = request.json
if 'size' not in data:
return jsonify({'error': 'size is required'}), 400
size = float(data['size'])
prediction = model.predict([[size]])[0]
return jsonify({
'input': {'size': size},
'predicted_price': round(prediction, 2)
})
@app.route('/api/health', methods=['GET'])
def health():
return jsonify({'status': 'healthy', 'model_loaded': model is not None})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)Education on Replit
Teams for Education
// FEATURES FOR TEACHERS
1. CLASSROOM MANAGEMENT
- Creating class teams
- Inviting students
- Assigning tasks
2. ASSIGNMENTS
- Creating starter projects
- Automated testing
- Due dates and grading
- Plagiarism detection
3. CURRICULUM
- Ready-made programming courses
- Interactive tutorials
- Completion certificates
4. MONITORING
- Real-time view of student work
- Edit history
- Progress analyticsEducational projects
# Example: Interactive Python Tutorial
def lesson_1_variables():
"""
LESSON 1: Variables in Python
Variables are 'boxes' for data. You can store
numbers, text, and other values in them.
"""
# Example - uncomment and run:
name = "Anna"
age = 25
height = 1.65
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height}m")
# TASK 1: Create variables describing your favorite hero
# hero_name = ???
# hero_power = ???
# hero_strength = ???
# Uncomment below when you're done:
# print(f"{hero_name} has power {hero_power} and strength {hero_strength}")
def lesson_2_conditionals():
"""
LESSON 2: Conditional statements
if-else lets you make decisions in code.
"""
age = 18
if age >= 18:
print("You are an adult!")
else:
print("You are a minor.")
# TASK 2: Write a program that checks whether a number is even
# number = int(input("Enter a number: "))
# if ???:
# print("Even")
# else:
# print("Odd")
# Run the lesson:
lesson_1_variables()Replit pricing (2025)
Free plan
Price: $0/month
Includes:
- Basic Repls (public)
- Ghostwriter (limited)
- Community support
- Replit Database (limited)
- Deployment for up to 3 apps
Replit Core plan
Price: $20/month
Includes:
- Private Repls
- Full Ghostwriter
- Replit Agent
- More resources (CPU, RAM)
- Faster Repls
- Priority support
- Boosted deployments
Teams Pro plan
Price: $40/user/month
Includes:
- Everything from Core
- Team management
- Shared Repls
- Centralized billing
- Admin controls
- SOC 2 compliance
Teams for Education
Price: Special offer for schools
Includes:
- Classroom management
- Assignments and grading
- Curriculum library
- Student analytics
- Plagiarism detection
Best practices
Project organization
// ✅ Good structure
my-project/
├── src/ # Source code
│ ├── routes/ # API routes
│ ├── models/ # Data models
│ ├── utils/ # Utilities
│ └── main.py # Entry point
├── tests/ # Tests
├── static/ # Static files
├── templates/ # HTML templates
├── .replit # Replit config
├── replit.nix # Nix config
├── requirements.txt # Dependencies
└── README.md # DocumentationPerformance
# Tips for better performance:
# 1. Use lightweight frameworks
# Flask instead of Django for small APIs
# Fastify instead of Express for Node.js
# 2. Lazy loading
from functools import lru_cache
@lru_cache(maxsize=100)
def expensive_operation(arg):
# Result will be cached
return compute(arg)
# 3. Asynchronous where possible
import asyncio
import aiohttp
async def fetch_data(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json()
# 4. Dependency optimization
# Don't install packages you don't use
# Use slim versions where availableSecurity
# Security best practices
# 1. Secrets in Environment Variables
import os
api_key = os.environ.get('API_KEY')
# NEVER: api_key = "hardcoded-key"
# 2. Input validation
from flask import request
from werkzeug.utils import secure_filename
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
filename = secure_filename(file.filename) # Sanitize!
# ...
# 3. CORS properly configured
from flask_cors import CORS
CORS(app, origins=['https://yourdomain.com'])
# 4. Rate limiting
from flask_limiter import Limiter
limiter = Limiter(app, key_func=get_remote_address)
@app.route('/api/resource')
@limiter.limit("100/hour")
def resource():
return dataFAQ - frequently asked questions
Are Repls always running?
Not by default. Free Repls "go to sleep" after a period of inactivity. For continuous operation:
- Use a Reserved VM deployment
- Or an external service like UptimeRobot to ping it
How do I persist files between restarts?
- Replit Database for key-value data
- SQLite/PostgreSQL for structured data
- External storage (S3, Cloudinary) for files
Can I use my own domain?
Yes! Custom domains are available on paid plans. Configuration via DNS CNAME or A record.
How do I debug in Replit?
print()statements- Built-in debugger (breakpoints)
- Ghostwriter for help with errors
- Console in the bottom panel
Is Replit good for production?
Yes, with some caveats:
- Autoscale may have cold starts
- Reserved VM for predictable performance
- Consider your own hosting for high traffic
Summary
Replit is a versatile development platform offering:
- Zero configuration - Start coding in seconds
- 50+ languages - From Python to Rust
- AI assistance - Agent and Ghostwriter
- Multiplayer - Team coding
- Deploy - From prototype to production
- Education - Perfect for teachers and students
Ideal for prototyping, learning to code, hobby projects, and small production applications.