DEV Community 👩‍💻👨‍💻

Cover image for Uploading a NodeJS web API to Heroku
LUCIANO DE SOUSA PEREIRA
LUCIANO DE SOUSA PEREIRA

Posted on

Uploading a NodeJS web API to Heroku

Objective

Upload a simple NodeJS web API to Heroku without using Docker.

Full example: https://github.com/lucianopereira86/NodeJS-Heroku.

Technologies

Topics

NodeJS

Create a directory for your NodeJS web API.

By running this command in a terminal, create a package.json file:

npm init

Edit the file by adding the following dependencies:

{
    ...
    "dependencies": {
        "cors": "^2.8.5",
        "express": "^4.16.4"
    }
    ...
}

Create the node_modules folder with this command:

npm install

Create an index.js file containing this code:

const express = require('express');
const app = express();
var cors = require('cors');

app.use(
    cors({
        credentials: true,
        origin: true
    })
);
app.options('*', cors());

app.get('/', (req, res) => res.send('Working!!!'));

app.listen(process.env.PORT || 3000, function() {
    console.log('server running on port 3000', '');
});

Run the web API with the following command:

node index

Open the browser with the URL below:

http://localhost:3000/

This will be the result:

node01

Your web API is WORKING!

Time to upload it to Heroku.

Heroku

Heroku is a cloud platform that allows applications be hosted at will. It's mostly used for web APIs. Go to Heroku website and sign up or sign in.

In your machine, install the latest version of Heroku CLI here.

In the web API root folder, create a Procfile, which is a Heroku file that specifies the commands that are executed by the app on startup. Write the following line within the file:

web: node index.js

Create a .git folder with this command:

git init

Create a .gitignore manually containing this line:

/node_modules

Your project will look like this:

node02

Authenticate with Heroku by running this command and follow the instructions that will be displayed in the terminal:

heroku login

Run the following command to create a project in Heroku. It will receive a random name but you can change it.

heroku create

Now, run the commands below to commit your web API to Heroku's new project:

git add *;
git commit -m "First commit";
git push heroku master;

The console will show the upload progress like this:

heroku01

Check if any error has occurred by running:

heroku logs

Finally, open the project by running this command:

heroku open

This will be the result:

heroku02

Conclusion

We have successfully uploaded our NodeJS web API to Heroku without using Docker.

Also, it was not needed to interact directly with Heroku website to create the app.

References

How To Deploy Nodejs App To Heroku

Top comments (0)

Image description

Join the One Year Club

You can earn this badge by being a registered member of the DEV Community for at least one year. Create an account and get started today.