/how-to-build-replit

How to Build a Recommendations engine with Replit

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

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

How to Build a Recommendations engine with Replit

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).

 

Set up your environment

 

Create a new Repl in Replit and choose a “Python” template if you’re doing this in Python, or “Node.js” if using JavaScript.

  • For Python, you get a main.py file automatically.
  • For Node.js, Replit gives you an index.js.

We’ll use Python here because it has excellent recommendation libraries and is easy to set up.

 

Create your recommendation logic

 

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

 

Connect your logic to a simple API

 

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)

 

Test your endpoint

 

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.)

 

Add persistence (optional)

 

  • To use a real database, you can create a file database.db and use SQLite. Replit includes SQLite by default in Python Repls.
  • Or create a free MongoDB Atlas cluster and store the connection string in Secrets (found in the left sidebar → “🔒 Secrets”). You can access it safely in your code using os.environ["MONGO\_URI"].

 

Common Replit-specific notes

 

  • Flask runs publicly by default, so don’t use any sensitive keys in query parameters.
  • If you need to save data that persists between runs, use a file or Replit DB (from replit import db) instead of in-memory dictionaries.
  • Every time you click “Run,” Replit reboots the container, so reinitializing large machine-learning models is slower — keep your logic light and cache results if possible.
  • For team collaboration, use Replit’s Multiplayer to let others modify and test recommendations.py together.

 

Final step: Integrate with frontend

 

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).

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Contact Us

How to Build a Simple Recommendation API with Express and Node.js


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"));

How to Build an AI-Powered Recommendations API with Express and OpenAI


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"));

How to Build a Recommendation API with Express, Replit Database, and Cosine Similarity


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"));

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Contact Us
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Best Practices for Building a Recommendations engine with Replit

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.

 

Project Structure

 

For a clean setup, create these files inside your Replit project root (each file visible in the left sidebar):

  • main.py or index.js — the main entry point of your app.
  • recommendation\_engine.py — where your recommendation logic lives (if using Python).
  • data.db — SQLite database file (automatically created by the app if it doesn’t exist).

 

Example: Python-based Recommendation Engine

 

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]]

 

Where to Place Code

 

  • Paste the first block in main.py.
  • Create a new file using the “New File” icon on the left, name it recommendation\_engine.py, and paste the second block there.
  • Click “Run” — Replit runs main.py by default for Python Repls.

 

How to Test It Inside Replit

 

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"

 

Best Practices on Replit

 

  • Use the Secrets tab (padlock icon on left bar) for sensitive info — DB URLs, API keys, etc. You can access them in Python with os.getenv('MY\_SECRET').
  • Commit your code to version control via the Git tool in Replit. The filesystem is not guaranteed to persist for free Repls if inactive.
  • Keep models small if using machine learning. For heavier computations, train offline and import a saved model (like a .pkl file) into Replit.
  • Inspect logs at the bottom console — Replit automatically streams print statements and stack traces there.
  • Don’t run CPU-heavy training interactively on free plans — it can cause timeouts (30 sec request cap). Move training to a separate script or external service.
  • Use Replit DB only for very lightweight key-value storage, not for complex recommendation data. SQLite or external DB (like Supabase, Neon, or MongoDB Atlas) is far better for real relationships between data.
  • Add requirements.txt listing needed Python packages:
    flask
    sqlite3 (built-in, no need to install separately)

 

Deployment Tips

 

  • Replit keeps your web app live when “Always On” is enabled (available on Hacker plan).
  • For collaborative dev, click the “Invite” button at top right — Replit multiplayer gives real-time co-editing.
  • Check your Logs for port conflicts or module import issues — Replit sometimes fails when nested imports use absolute paths; use relative imports like 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.

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022