paint-brush
Build a Movie Streaming App Like Netflix Using Node.js, MySQL, and Deploy on Aptibleby@wise4rmgod
1,961 reads
1,961 reads

Build a Movie Streaming App Like Netflix Using Node.js, MySQL, and Deploy on Aptible

by Wisdom NwokochaOctober 3rd, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Imagine watching your favorite movies and TV shows anytime, anywhere, without worrying about buffering or slow loading times. That's the power of a movie streaming web app like Netflix. But what if you could build your own movie streaming web app without managing the infrastructure? That's where Aptible comes in.
featured image - Build a Movie Streaming App Like Netflix Using Node.js, MySQL, and Deploy on Aptible
Wisdom Nwokocha HackerNoon profile picture

Imagine watching your favorite movies and TV shows anytime, anywhere, without worrying about slow loading times. That's the power of a movie streaming web app like Netflix.


But what if you could build your movie streaming web app without managing the infrastructure? That's where Aptible comes in.


Aptible is a platform that streamlines the code shipping process for development teams, facilitating deployment, monitoring, and infrastructure scaling. This means you can focus on building your app while Aptible takes care of the rest.

https://www.tutorialspoint.com/cloud_computing/cloud_computing_platform_as_a_service.htm


This article will show you how to build a movie streaming web app like Netflix using Aptible, from choosing the right technologies to deploying your app to production.

Choosing the right technologies for a streaming web app

  1. Scalability: Streaming web apps need to handle many users and a high traffic volume. The technologies you choose should be able to scale to meet the demands of your app.
  2. Performance: Streaming web apps need to deliver a high-quality user experience. This means that the technologies you choose should be able to deliver video and audio content quickly and smoothly.
  3. Security: Streaming web apps need to be secure. The technologies you choose should be able to protect your users' data and prevent unauthorized access to your app.
  4. Cost: Streaming web apps can be expensive to build and maintain. The technologies you choose should be cost-effective and scalable to meet your budget.


Node.js, MySQL, and Aptible are well-suited technologies for building scalable, performant, and secure streaming web apps.

What are the benefits of using Aptible to build a movie streaming web app?


  1. Simplified deployment

Aptible makes it easy to deploy your movie streaming web app to production. You can upload your code to Aptible, and it will take care of the rest, including setting up the necessary infrastructure and configuring your app.


  1. Automatic scaling

Aptible can automatically scale your movie streaming web app up or down based on demand. This is important for movie streaming apps, which can experience spikes in traffic at certain times of the day or during popular movie releases.


  1. Built-in monitoring

Aptible provides built-in monitoring for your movie streaming web app. You can track your app's performance and identify potential problems early on.


Aptible provides a variety of metrics, including CPU usage, memory usage, and response times, which can help you keep your movie streaming web app running smoothly and prevent major outages.


  1. Security features

Aptible provides various security features to protect your movie streaming web app from attack. These features include:


  • Firewalls: Aptible provides firewalls to protect your app from unauthorized access.
  • Intrusion detection systems (IDS): Aptible provides IDS to detect and block malicious traffic.
  • Data encryption: Aptible encrypts your app's data at rest and in transit.


  1. Teams:

Aptible's team’s feature allows you to create groups of users and assign different permissions to each team.


  1. Environments:

Aptible's environments feature allows you to create multiple isolated environments for your app. This can be useful for testing your app and deploying changes in a controlled manner.


  1. Backups:

Aptible automatically backs up your app's data regularly. This can help you recover your data in case of a problem, such as a hardware failure or a software bug.


  1. Support:

Aptible provides 24/7 support to help you with any problems you may have. You can contact Aptible's support team via email, chat, or phone.


Build a movie app using Node.js and MySQL

Prerequisites:

  • Basic knowledge of JavaScript, Node.js, and MySQL.
  • Node.js and npm (Node Package Manager) are installed on your system.
  • A MySQL database server is installed and running.
  • A basic knowledge of phpMyAdmin.
  • A good knowledge of using the Aptible platform to create databases, environments, and apps.


Step 1: Set Up MySQL Database

First, you need to create a MySQL database to store movie information. In this tutorial, you will use phpMyAdmin.


Create a new database and a table for movies:

CREATE DATABASE movie_db;
USE movie_db;

CREATE TABLE movies (
    id INT AUTO_INCREMENT PRIMARY KEY,
    image_url VARCHAR(255) NOT NULL,
    video_url VARCHAR(255) NOT NULL,
    title VARCHAR(255) NOT NULL,
    genre VARCHAR(255) NOT NULL,
    description TEXT,
    rating DECIMAL(3, 1),
    release_year INT
);

Step 2: Set Up Node.js Project

Please create a new Node.js project folder and initialize it as a Node.js project.

mkdir movie-app
cd movie-app
npm init -y


Install the required dependencies:

npm install express mysql2 multer


  • express: A popular Node.js framework for building web applications.
  • mysql2: A MySQL client for Node.js.
  • multer: Middleware for handling file uploads.

Step 3: Create a Database Connection

In your Node.js project, create a db.js file to set up the MySQL database connection:

// db.js
const mysql = require('mysql2');

const db = mysql.createConnection({
  host: 'localhost', // Change to your MySQL host
  user: 'root',      // Change to your MySQL username
  password: 'password', // Change to your MySQL password
  database: 'movie_db',
});

db.connect((err) => {
  if (err) {
    console.error('Error connecting to the database:', err);
    throw err;
  }
  console.log('Connected to the database');
});

const createTable = `
  CREATE TABLE IF NOT EXISTS movies (
    id INT AUTO_INCREMENT PRIMARY KEY,
    image_url VARCHAR(255) NOT NULL,
    video_url VARCHAR(255) NOT NULL,
    title VARCHAR(255) NOT NULL,
    genre VARCHAR(255) NOT NULL,
    description TEXT,
    rating DECIMAL(3, 1),
    release_year INT
  )
`;

db.query(createTable, (err) => {
  if (err) {
    console.error("Error creating movies table:", err);
  } else {
    console.log("Movies table created or already exists");
  }
});

module.exports = db;


Replace 'your_username' and 'your_password' with your MySQL credentials.

Step 4: Create API Endpoints

In your Node.js project, create an app.js file to define your API endpoints using Express:

// app.js
const express = require('express');
const db = require('./db'); // Import the database connection
const multer = require('multer');

const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Configure Multer for handling file uploads
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + '-' + file.originalname);
  },
});

const upload = multer({ storage });

// Create a new movie
app.post('/movies', upload.fields([{ name: 'image', maxCount: 1 }, { name: 'video', maxCount: 1 }]), (req, res) => {
  const { title, genre, description, rating, release_year } = req.body;
  const image_url = req.files['image'][0].path;
  const video_url = req.files['video'][0].path;

  const query = 'INSERT INTO movies (image_url, video_url, title, genre, description, rating, release_year) VALUES (?, ?, ?, ?, ?, ?, ?)';
  const values = [image_url, video_url, title, genre, description, rating, release_year];

  db.query(query, values, (err, result) => {
    if (err) {
      console.error('Error creating a movie:', err);
      res.status(500).json({ error: 'Internal Server Error' });
    } else {
      res.status(201).json({ message: 'Movie created successfully' });
    }
  });
});

// List all movies
app.get('/movies', (req, res) => {
  const query = 'SELECT * FROM movies';

  db.query(query, (err, rows) => {
    if (err) {
      console.error('Error listing movies:', err);
      res.status(500).json({ error: 'Internal Server Error' });
    } else {
      res.status(200).json(rows);
    }
  });
});

// Search movies
app.get('/movies/search', (req, res) => {
  const { query } = req.query;
  const searchQuery = `%${query}%`;

  const searchSql = 'SELECT * FROM movies WHERE title LIKE ? OR genre LIKE ?';
  const searchValues = [searchQuery, searchQuery];

  db.query(searchSql, searchValues, (err, rows) => {
    if (err) {
      console.error('Error searching movies:', err);
      res.status(500).json({ error: 'Internal Server Error' });
    } else {
      res.status(200).json(rows);
    }
  });
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Endpoints

Base URL: http://localhost:3000/

1. Create a New Movie

  • Endpoint: /movies
  • Method: POST
  • Description: Create a new movie and add it to the database.

Request

  • Body:

    {
      "title": "Movie Title",
      "description": "Movie description goes here.",
      "release_year": 2023,
      "genre": "Action",
      "rating": 8.5,
      "image_url": "https://example.com/movie-image.jpg",
      "video_url": "https://example.com/movie-video.mp4"
    }
    


Response

  • Status: 201 Created

  • Body:

    jsonCopy code{
      "message": "Movie created successfully"
    


2. List All Movies

  • Endpoint: /movies
  • Method: GET
  • Description: Get a list of all available movies.

Response

  • Status: 200 OK

  • Body: An array of movie objects. Each object includes the following fields:

    jsonCopy code[
      {
        "id": 1,
        "title": "Movie Title 1",
        "description": "Movie description goes here.",
        "release_year": 2022,
        "genre": "Drama",
        "rating": 7.9,
        "image_url": "https://example.com/movie1-image.jpg",
        "video_url": "https://example.com/movie1-video.mp4"
      },
      {
        "id": 2,
        "title": "Movie Title 2",
        "description": "Another movie description.",
        "release_year": 2021,
        "genre": "Comedy",
        "rating": 6.8,
        "image_url": "https://example.com/movie2-image.jpg",
        "video_url": "https://example.com/movie2-video.mp4"
      }
    ]
    


Step 5: Test your code

Start your app by running the following command:

node app.js


Once your app runs, you can test the endpoints using an API testing platform.

Testing the endpoints


You can check your phpMyAdmin interface to confirm the data was saved successfully.

phpMyAdmin interface

Step 6: Push your project to GitHub

  • Create a new repository on GitHub and clone it to your local machine.
  • Make your changes to the code and commit them.
  • Push your changes to GitHub.

Once you have pushed your code to GitHub, you can deploy it to Aptible.


Code folder structure

code folder structure


To see the complete codebase, please check out my GitHub repository at https://github.com/wise4rmgod/moviedb

Deploying your application to Aptible

1: Create environment

  • Go to the Aptible dashboard and click on the Environments tab.

  • Click on the Create Environment button.

  • Enter a name for the environment and select the appropriate region.

  • Click on the Create Environment button.


create environment in aptible


2: Create Database

In this tutorial, you will create a MySQL database.

create database in aptible


After creating the database, go to the dashboard and click on the reveal to see your connection URL

database credentials

To avoid this error

ERROR 1045 (28000): Access denied for user 'aptible'@'ip-[IP_ADDRESS].ec2.internal' (using password: YES)


Add this field to your db.js

ssl: { rejectUnauthorized: false, ciphers: "DHE-RSA-AES256-SHA" },


Complete db.js

const mysql = require("mysql2");

const db = mysql.createConnection({
  host: "", // Change to your MySQL aptible host
  user: "aptible", // Change to your MySQL username
  password: "", // Change to your MySQL password
  database: "db",
  ssl: { rejectUnauthorized: false, ciphers: "DHE-RSA-AES256-SHA" },
  port: 26038,
});

db.connect((err) => {
  if (err) {
    console.error("Error connecting to the database:", err);
    throw err;
  }
  console.log("Connected to the database");
});

const createTable = `
  CREATE TABLE IF NOT EXISTS movies (
    id INT AUTO_INCREMENT PRIMARY KEY,
    image_url VARCHAR(255) NOT NULL,
    video_url VARCHAR(255) NOT NULL,
    title VARCHAR(255) NOT NULL,
    genre VARCHAR(255) NOT NULL,
    description TEXT,
    rating DECIMAL(3, 1),
    release_year INT
  )
`;

db.query(createTable, (err) => {
  if (err) {
    console.error("Error creating movies table:", err);
  } else {
    console.log("Movies table created or already exists");
  }
});

module.exports = db;


3: Create an App

Then, create an App by giving the Handle a name, and click Save App

app name

Aptible will take some time to provision your app


Once provisioning is complete, click on the app name and click Get Started to continue the deployment process.


4: Upload your SSH public key.

  • In your dashboard, click on your name in the top right corner and select SSH Keys.
  • Click on the Add SSH Key button.
  • Paste your SSH public key into the text box and click on the Add SSH Key button.

ssh key


5: Create a Dockerfile

Sample Dockerfile here

# Use the official Node.js image as the base image
FROM node:16

# Set the working directory inside the container
WORKDIR /app

# Copy package.json and package-lock.json to the working directory
COPY package*.json ./

# Install project dependencies
RUN npm install

# Copy the application code to the container
COPY . .

# Expose the port that the app will run on
EXPOSE 3000

# Start the application
CMD ["node", "app.js"]


6: Deploy to Aptible via Git remote


The Aptible Git remote URL is specific to your account. You can find it in the Get Started tab of your app's dashboard.

Add the Aptible Git remote for this app, then push to the remote to begin deployment:

git remote add aptible [email protected]:env-prodzz/movieapp.git 


Push your code to Aptible.

git push aptible main


If successful, you will see an image similar to the following.

Success!



7: Add an Endpoint

  • In your app, click on the Endpoints tab.
  • Click on the Create Endpoint button.

created aptible endpoint


Once the endpoint has been created, you can send a GET, POST, DELETE, or any other supported HTTP method to the endpoint using an API testing platform.


To test the endpoint, copy the HOSTNAME from the endpoint's dashboard and use it in your API testing platform.


8: Test your final project

Testing your project


Conclusion

In this article, you learned how to build a movie streaming app like Netflix using Node.js, MySQL, and Aptible. You also learned about the benefits of using these technologies for building streaming web apps and the steps involved in deploying a Node.js app to Aptible.


If you want to build a movie streaming app like Netflix, I recommend using Node.js, MySQL, and Aptible. These technologies are well-suited for building scalable, performant, secure streaming web apps.