Building a Movie Recommendation Engine Using Node.js and JavaScript

09 Feb 2025  Amiya pattanaik  3 mins read.

Introduction

Movie recommendation systems are widely used in streaming platforms to suggest films based on user preferences. In this blog post, we will build a simple movie recommendation engine using Node.js and JavaScript.

Prerequisites

To follow this guide, you should have:

  • Basic knowledge of JavaScript and Node.js.

  • Node.js and npm installed on your machine.

  • A code editor (like VS Code) installed.

Step 1: Setting Up the Project:

  1. Create a new directory for your project and navigate to it:
    • mkdir movie-recommender && cd movie-recommender
  2. Initialize a new Node.js project:
    • npm init -y
  3. Install the required dependencies:
    • npm install express cors simple-statistics

Express: A web framework for building APIs and handling HTTP requests.

COR: Enables cross-origin requests..

Simple-statistics: A library for handling similarity calculations.

Step 2: Creating the Dataset

Create a new file movies.json to store movie data:

[
  { "id": 1, "title": "Inception", "category": ["Sci-Fi", "Thriller"], "ratings": [5, 4, 5, 5] },
  { "id": 2, "title": "Interstellar", "category": ["Sci-Fi", "Drama"], "ratings": [5, 5, 5, 4] },
  { "id": 3, "title": "The Dark Knight", "category": ["Action", "Thriller"], "ratings": [5, 5, 4, 5] },
  { "id": 4, "title": "The Matrix", "category": ["Sci-Fi", "Action"], "ratings": [5, 4, 4, 5] },
  { "id": 5, "title": "Fight Club", "category": ["Drama", "Thriller"], "ratings": [4, 5, 4, 4] }
]

Step 3: Building the Recommendation API

Create a server.js file and set up the API:

const express = require('express');
const cors = require('cors');
const ss = require('simple-statistics');
const movies = require('./movies.json');

const app = express();
const PORT = 3000;

app.use(cors());
app.use(express.json());

// Function to calculate movie similarity based on ratings
function recommendMovies(movieId) {
  const targetMovie = movies.find(m => m.id === movieId);
  if (!targetMovie) return [];

  return movies
    .filter(m => m.id !== movieId)
    .map(m => {
      const similarity = ss.pearsonCorrelation(targetMovie.ratings, m.ratings);
      return { title: m.title, similarity };
    })
    .sort((a, b) => b.similarity - a.similarity);
}

app.get('/recommend/:id', (req, res) => {
  const movieId = parseInt(req.params.id);
  const recommendations = recommendMovies(movieId);
  res.json(recommendations);
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Step 4: Testing the API

Start your server:

- node server.js

Open your browser or use Postman to request movie recommendations: http://localhost:3000/recommend/1.

This will return a list of recommended movies based on similarity.

Step 5: Building a Simple Frontend

Create a public/index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Movie Recommender</title>
</head>
<body>
  <h1>Movie Recommendation System</h1>
  <input type="number" id="movieId" placeholder="Enter Movie ID">
  <button onclick="getRecommendations()">Get Recommendations</button>
  <ul id="recommendations"></ul>

  <script>
    function getRecommendations() {
      const movieId = document.getElementById('movieId').value;
      fetch(`http://localhost:3000/recommend/${movieId}`)
        .then(response => response.json())
        .then(data => {
          const list = document.getElementById('recommendations');
          list.innerHTML = '';
          data.forEach(movie => {
            const item = document.createElement('li');
            item.textContent = `${movie.title} (Similarity: ${movie.similarity.toFixed(2)})`;
            list.appendChild(item);
          });
        });
    }
  </script>
</body>
</html>

Conclusion

We have now built a simple movie recommendation engine using Node.js and JavaScript! You can enhance this system by:

  • Adding more movie attributes like director, actors, or keywords.

  • Using collaborative filtering to improve recommendations.

  • Implementing a real database instead of JSON.

  • Let me know if you have any questions or ideas to improve this system! 🚀

We encourage our readers to treat each other respectfully and constructively. Thank you for taking the time to read this blog post to the end. We look forward to your contributions. Let’s make something great together! What do you think? Please vote and post your comments.

Amiya Pattanaik
Amiya Pattanaik

Amiya is a Product Engineering Director focus on Product Development, Quality Engineering & User Experience. He writes his experiences here.