Learn how to build a powerful recommendation engine using Replit. Follow step-by-step guidance to create smart, data-driven suggestions easily.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
To build a recommendations engine on Replit, the most reliable way is to create a simple Python or Node.js backend that computes recommendations based on data stored in a local file or connected database (like Replit’s built-in SQLite or an external service such as MongoDB Atlas). You’ll train or simulate a small recommendation system (for instance, by using collaborative filtering or content-based filtering) and expose it through an API endpoint that your front-end (React, HTML, etc.) can call. On Replit, store your data in a file or database, write a recommendation logic in a separate module, and run your project from a single main.py (for Python) or index.js (for Node).
Create a new Repl in Replit and choose a “Python” template if you’re doing this in Python, or “Node.js” if using JavaScript.
We’ll use Python here because it has excellent recommendation libraries and is easy to set up.
Inside your Replit, click “Add file” and create a new file called recommendations.py. This file will contain the actual recommendation function.
# recommendations.py
import math
// A sample dataset - in a real project, store it in a database
user_ratings = {
"Alice": {"Inception": 5, "Titanic": 3, "Avatar": 4},
"Bob": {"Inception": 4, "Titanic": 2, "Avatar": 5},
"Charlie": {"Inception": 2, "Titanic": 4, "Avatar": 3}
}
// Function to calculate similarity score between two users
def similarity(person1, person2):
common = set(user_ratings[person1]).intersection(user_ratings[person2])
if not common:
return 0
sum_of_squares = sum([(user_ratings[person1][movie] - user_ratings[person2][movie]) ** 2 for movie in common])
return 1 / (1 + math.sqrt(sum_of_squares))
// Recommend movies for a person based on others with similar taste
def get_recommendations(person):
totals = {}
sim_sums = {}
for other in user_ratings:
if other == person:
continue
sim = similarity(person, other)
if sim <= 0:
continue
for movie in user_ratings[other]:
if movie not in user_ratings[person]:
totals.setdefault(movie, 0)
totals[movie] += user_ratings[other][movie] * sim
sim_sums.setdefault(movie, 0)
sim_sums[movie] += sim
rankings = [(total / sim_sums[movie], movie) for movie, total in totals.items()]
rankings.sort(reverse=True)
return rankings
Now go back to main.py and create a small web API using Flask (a lightweight Python web framework). This allows you or your front-end to get recommendations via HTTP. Install Flask in Replit’s shell first by typing:
pip install flask
Then update your main.py like this:
# main.py
from flask import Flask, request, jsonify
from recommendations import get_recommendations
app = Flask(__name__)
// A simple endpoint to test recommendations
@app.route('/recommend', methods=['GET'])
def recommend():
user = request.args.get('user')
if not user:
return jsonify({"error": "Please provide ?user=Name"})
recs = get_recommendations(user)
return jsonify({"recommendations": recs})
// Run on Replit (it will give you a public URL automatically)
app.run(host='0.0.0.0', port=3000)
Click the green “Run” button in Replit. You’ll see a small log that Flask is running. Click the “Open in a new tab” button, and Replit’s URL will look like:
https://your-repl-name.username.repl.co/recommend?user=Alice
This will return JSON results like:
{"recommendations": [[4.5, "Titanic"]]}
(That means for Alice, Titanic is recommended with predicted rating 4.5.)
os.environ["MONGO\_URI"].
from replit import db) instead of in-memory dictionaries.
If you have a React frontend hosted on Replit (or any other frontend), call this Flask API endpoint with fetch():
// Example from your React component
fetch('https://your-repl-name.username.repl.co/recommend?user=Alice')
.then(res => res.json())
.then(data => {
console.log(data.recommendations)
})
This full setup gives you a working recommendation engine that’s practical to test and deploy entirely inside Replit, with a clear structure (main.py for server, recommendations.py for logic, optional database for persistence).
const express = require("express");
const app = express();
const fs = require("fs");
app.use(express.json());
const DATA_FILE = "user_data.json";
function loadData() {
if (!fs.existsSync(DATA_FILE)) fs.writeFileSync(DATA_FILE, JSON.stringify({ users: {} }));
return JSON.parse(fs.readFileSync(DATA\_FILE, "utf8"));
}
function saveData(data) {
fs.writeFileSync(DATA\_FILE, JSON.stringify(data, null, 2));
}
function getRecommendations(userId, data, limit = 5) {
const user = data.users[userId];
if (!user) return [];
const allUserIds = Object.keys(data.users).filter(id => id !== userId);
const scores = allUserIds.map(id => {
const commonItems = user.items.filter(i => data.users[id].items.includes(i));
return { id, score: commonItems.length };
});
const sorted = scores.sort((a, b) => b.score - a.score);
const topMatches = sorted.slice(0, limit).map(u => u.id);
const recs = new Set();
topMatches.forEach(uid => {
data.users[uid].items.forEach(i => {
if (!user.items.includes(i)) recs.add(i);
});
});
return Array.from(recs).slice(0, limit);
}
app.post("/api/addUser", (req, res) => {
const { userId, items } = req.body;
const data = loadData();
data.users[userId] = { items };
saveData(data);
res.json({ status: "ok" });
});
app.get("/api/recommend/:userId", (req, res) => {
const data = loadData();
const recs = getRecommendations(req.params.userId, data);
res.json({ recommendations: recs });
});
app.listen(3000, () => console.log("Server running on port 3000"));
import express from "express";
import fetch from "node-fetch";
const app = express();
app.use(express.json());
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
app.post("/api/recommendations", async (req, res) => {
try {
const { userId, interests } = req.body;
// Call external recommendation model (e.g. OpenAI embedding-based search)
const response = await fetch("https://api.openai.com/v1/embeddings", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: "text-embedding-3-small",
input: interests.join(", "),
}),
});
const data = await response.json();
const userEmbedding = data.data[0].embedding;
// Example: send embedding to your external vector DB
const vectorRes = await fetch("https://your-vector-db.example.com/query", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
vector: userEmbedding,
topK: 5,
}),
});
const recommendations = await vectorRes.json();
res.json({ userId, recommendations });
} catch (err) {
console.error(err);
res.status(500).json({ error: "Failed to fetch recommendations" });
}
});
app.listen(3000, () => console.log("Server running on port 3000"));
import express from "express";
import Database from "@replit/database";
import crypto from "crypto";
const app = express();
const db = new Database();
app.use(express.json());
async function computeSimilarities(userId, targetVector, topN = 5) {
const all = await db.get("profiles") || {};
const scores = Object.entries(all)
.filter(([id]) => id !== userId)
.map(([id, profile]) => {
const sim = cosineSimilarity(targetVector, profile.vector);
return { id, sim, interests: profile.interests };
})
.sort((a, b) => b.sim - a.sim)
.slice(0, topN);
return scores;
}
function cosineSimilarity(a, b) {
const dot = a.reduce((sum, val, i) => sum + val \* b[i], 0);
const magA = Math.sqrt(a.reduce((sum, val) => sum + val \* val, 0));
const magB = Math.sqrt(b.reduce((sum, val) => sum + val \* val, 0));
return dot / (magA \* magB);
}
app.post("/api/profile", async (req, res) => {
const { userId, interests } = req.body;
const vector = crypto
.createHash("sha256")
.update(interests.join(","))
.digest()
.slice(0, 8)
.map(b => b / 255);
const profiles = await db.get("profiles") || {};
profiles[userId] = { interests, vector };
await db.set("profiles", profiles);
res.json({ status: "saved", userId });
});
app.get("/api/recommend/:userId", async (req, res) => {
const profiles = await db.get("profiles") || {};
const user = profiles[req.params.userId];
if (!user) return res.status(404).json({ error: "User not found" });
const similar = await computeSimilarities(req.params.userId, user.vector);
const suggested = [
...new Set(
similar.flatMap(u => u.interests)
.filter(i => !user.interests.includes(i))
),
].slice(0, 5);
res.json({ recommendations: suggested });
});
app.listen(3000, () => console.log("Recommendation API running"));

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
The best practice when building a recommendations engine on Replit is to separate your logic cleanly, use persistent storage (like SQLite or an external database) for user-item data, and keep compute-heavy or long-running training outside the main request cycle. Replit can absolutely handle small- to mid-scale recommendation tasks — like generating product, music, or content suggestions — as long as you manage dependencies, background work, and resource usage carefully. Use Python Repls for data and recommendation logic, or a Node.js Repl if your front end is JavaScript-based. Keep secrets (like DB credentials or API keys) safely in Replit’s Secrets tab, and plan storage wisely since the Replit filesystem resets on reboot unless you commit to Git or use a persistent database.
For a clean setup, create these files inside your Replit project root (each file visible in the left sidebar):
This example shows a simple Python content-based recommendation using SQLite. The logic can be easily upgraded later to collaborative filtering or ML-based approaches.
# main.py
from flask import Flask, request, jsonify
import sqlite3
from recommendation_engine import get_recommendations
app = Flask(__name__)
# Simple setup: database connection helper
def get_db_connection():
conn = sqlite3.connect('data.db')
conn.row_factory = sqlite3.Row # so we can access columns by name
return conn
@app.route('/add_item', methods=['POST'])
def add_item():
data = request.get_json()
name = data['name']
tags = data['tags'] # comma-separated tags describing the item
conn = get_db_connection()
conn.execute('INSERT INTO items (name, tags) VALUES (?, ?)', (name, tags))
conn.commit()
conn.close()
return jsonify({'message': 'Item added!'})
@app.route('/recommend', methods=['GET'])
def recommend():
item_name = request.args.get('item')
recommendations = get_recommendations(item_name)
return jsonify({'recommendations': recommendations})
if __name__ == '__main__':
# Create DB table if not exists
conn = sqlite3.connect('data.db')
conn.execute('CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, name TEXT, tags TEXT)')
conn.close()
# Run Flask app — Replit auto-exposes on default port 8080
app.run(host='0.0.0.0', port=8080)
# recommendation_engine.py
import sqlite3
def get_recommendations(item_name):
conn = sqlite3.connect('data.db')
conn.row_factory = sqlite3.Row
items = conn.execute('SELECT * FROM items').fetchall()
conn.close()
# Find the target item
target = next((item for item in items if item['name'] == item_name), None)
if not target:
return []
target_tags = set(target['tags'].split(','))
scores = []
for item in items:
if item['name'] == item_name:
continue
tags = set(item['tags'].split(','))
similarity = len(target_tags.intersection(tags))
scores.append((item['name'], similarity))
# Sort by score descending
scores.sort(key=lambda x: x[1], reverse=True)
# Return top 3 recommendations
return [name for name, _ in scores[:3]]
Once it’s running, click the “Open in a new tab” icon next to your web preview. Then use the Replit “Shell” tab to test endpoints using curl or Replit’s built-in HTTP client.
curl -X POST -H "Content-Type: application/json" -d '{"name":"Book A","tags":"fiction,classic,novel"}' https://<your-repl-url>.repl.co/add_item
curl -X POST -H "Content-Type: application/json" -d '{"name":"Book B","tags":"fiction,thriller"}' https://<your-repl-url>.repl.co/add_item
curl "https://<your-repl-url>.repl.co/recommend?item=Book%20A"
os.getenv('MY\_SECRET').flask
sqlite3 (built-in, no need to install separately)
from recommendation_engine import get_recommendations.
This setup gives you a small but functional recommendations engine directly on Replit, realistic for prototypes or small projects, and can grow later into a production-grade service by swapping SQLite for Postgres, replacing similarity heuristics with ML embeddings, or containerizing outside Replit when scale demands it.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.