Node + React Archives | Talent500 blog https://talent500.com/blog/category/fullstack/node-react/ Tue, 28 Mar 2023 09:02:37 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 https://talent500.com/blog/wp-content/uploads/sites/42/2025/01/favicon.ico Node + React Archives | Talent500 blog https://talent500.com/blog/category/fullstack/node-react/ 32 32 How to Set Up and Send Mails Using SendGrid in NodeJs App? https://talent500.com/blog/how-to-set-up-and-send-mails-using-sendgrid-in-nodejs-app/ https://talent500.com/blog/how-to-set-up-and-send-mails-using-sendgrid-in-nodejs-app/#respond Tue, 28 Mar 2023 09:02:37 +0000 https://talent500.com/blog/?p=36774 Introduction Email is an essential part of modern communication, and it’s crucial to have a reliable email delivery system in […]

The post How to Set Up and Send Mails Using SendGrid in NodeJs App? appeared first on Talent500 blog.

]]>
Introduction

Email is an essential part of modern communication, and it’s crucial to have a reliable email delivery system in your Node.js app. SendGrid is a cloud-based email delivery service that allows you to send emails from your app. It provides a simple and efficient way to send emails without worrying about email server setup, email throttling, or email blacklist issues. In this guide, we will walk you through the steps to set up and send emails using SendGrid in your Node.js app, we will cover everything you need to know to get started with SendGrid.

Set Up and Send Mails Using SendGrid in NodeJs App

What is SendGrid?

SendGrid is an SMTP (Simple Mail Transmission Protocol) service provider. We trust you’re familiar with SMTP. It saves your time and effort while also giving you more freedom when sending large amounts of emails.

Why use SendGrid in NodeJS to Send Emails?

Below are the reasons why you should use SendGrid for sending emails.

  • A powerful email solution for delivering large amounts of email with good deliverability rates.
  • Offers interactive and eye-catching built-in email templates, as well as the ability to alter them.
  • SendGrid allows you to track the real-time performance of emails using data like bounce rates, unsubscribers, delivered emails rate, unique reads/opens/clicks, and many more.
  • Excellent customer service
  • Sendgrid is linked with so many tools that you can consolidate your marketing efforts. API integration with many tools is really strong.

A: Initial Project Setup

1.Using the below command, create a NodeJs application.

mkdir SendgridApp

cd SendgridApp

 

2.Initializing the Project
npm init -y


3.This creates a package.json file.

Using the below command, install the required dependencies in our project.

npm i express @sendgrid/mail dotenv

Open the root file of your project and name it as you wish.

// app.js

const express = require(“express”);

require(“dotenv”).config();

var app = express();

app.use(express.json())

const mailRoute = require(‘./routes/sendMail’)

app.use(mailRoute)

app.listen(process.env.PORT, console.log(‘Server is up and running ‘+ process.env.PORT))

 

B: Setting Up SendGrid Account

Let’s start with integrating Sendgrid.

Follow these instructions to set up the SendGrid account, –

  1. Go to SendGrid.com.
  2. Establish a user account
  3. Pick a plan that meets your needs.
  4. Create an API key

We must configure the SendGrid API key in the application before we can send emails from the NodeJS app. SendGrid allows you to create an email based on your needs. We can also add and change HTML, photos, documents, and so on.

// email/account.js

const sgMail = require(‘@sendgrid/mail’)

require(‘dotenv’).config()

sgMail.setApiKey(process.env.SENDGRID_API_KEY) //your sendgrid api key

 

const sendMail = (email, name) => {

    sgMail.send({

        To: email, // receiver email address

        from: ‘fromemail@email.com’, 

        subject: ‘here comes subject line’, 

        text: `here comes the body ${name}` 

    })

}

 

module.exports = {

    sendMail

}


C: Send Mails using SendGrid in NodeJs App

We may utilise the sendgrid method anywhere we need, such as when a user registers or leaves, or for other alerts.

// sendMail.js

In this example, we are sending mail for a certain route and using sendMail methods as needed.

const express = require(‘express’)

const { append } = require(‘express/lib/response’)

const { sendMail } = require(‘../emails/accounts’)

const statusCode = require(‘../constants/constants’)

 

const router = new express.Router()

 

router.get(‘/sendmail’, (req, res) => {

const user = req.body;

    try {

        sendMail(user.email,user.name)

        res.status(statusCode.ok).send({message: ‘Mail Sent’})

    } catch (error) {

        res.status(statusCode.internalServerError).send({error})

    }

})

 

module.exports = router


In this case, we manually specify the email or other essential parameters that we may send using Postman.

Conclusion

In this blog, we learned how to send emails using Node.js using SendGrid. We can send various transactional emails, including the order confirmation. Sending emails using Node.js and SendGrid becomes a snap if the email system is properly configured and templates are dynamic.

Setting up and sending emails using SendGrid in a Node.js app is a straightforward process that can be accomplished with just a few steps. By registering for a free SendGrid account, creating an API key, and installing the necessary packages, you can start sending emails from your app using SendGrid’s reliable email delivery system. With the help of the tutorials and code examples mentioned in this guide, you can easily integrate SendGrid into your Node.js app and start sending transactional emails. We encourage you to explore more Node.js tutorials and resources to further enhance your skills and knowledge. 

 

The post How to Set Up and Send Mails Using SendGrid in NodeJs App? appeared first on Talent500 blog.

]]>
https://talent500.com/blog/how-to-set-up-and-send-mails-using-sendgrid-in-nodejs-app/feed/ 0
How to Build Microservices with Node.js https://talent500.com/blog/how-to-build-microservices-with-node-js/ https://talent500.com/blog/how-to-build-microservices-with-node-js/#respond Tue, 28 Mar 2023 08:47:08 +0000 https://talent500.com/blog/?p=36769 Microservices are an architectural style that has gained popularity in recent years due to its ability to help build scalable […]

The post How to Build Microservices with Node.js appeared first on Talent500 blog.

]]>
Microservices are an architectural style that has gained popularity in recent years due to its ability to help build scalable and flexible systems. With this approach, applications are broken down into smaller, independent services that can be developed and deployed separately, allowing for faster iteration and better fault tolerance. Node.js, with its non-blocking I/O and lightweight runtime, is a great choice for building microservices. In this guide, we’ll explore the key concepts of microservices and show you how to build microservices with Node.js.

The blog will consist of simple steps that can be followed to start building your own demo app.

Microservices with Node.js Example

In this showcase application, we will use NodeJS to create microservices that will connect to an external API.

There will be three services in the app: Book, Customer, and Order. Individual servers will be running on various ports for each service. REST APIs will be used to communicate between these services. We are all aware that without microservices architecture, we would only have one server functioning. The situation is different with microservices architecture.

So, that’s what we’re developing in this lesson; now let’s get started with the code.

Initial Set-Up

Make sure you have Node.js installed if your system doesn’t have Node.js. To download the latest Node version, Visit Nodejs.org.

In the project root folder, run npm init. This will generate a package.json file with questions about the package; if you are unsure how to reply, use the default.

We will be using four packages Express, mongoose, axios, and dotenv which can be installed as follows:

$ npm install express mongoose axios dotenv –save

Project Structure

The project structure is depicted in the graphic below. The structure might differ from one individual to the next.

Creating Database Connection

Let’s begin with the fundamental step of establishing a database connection. Create a db.js file in the db subdirectory to code the database connection. This is simply a modest example project, but larger and more complicated systems use separate databases for each service.

// db.js

const mongoose = require(‘mongoose’);

mongoose.connect(process.env.MONGO_URI, { 

     useNewUrlParser: true,

     useUnifiedTopology: true,

     useFindAndModify: false,

     useCreateIndex: true

}).then(() => {

     console.log(‘Connection successful!’);

}).catch((e) => {

     console.log(‘Connection failed!’);

})


For a MongoDB database connection, we must use the mongoose package in db.js.

The connect() method will accept two arguments: uri and options.

Creating Book Service

Make a Book folder for the Book service, and inside it, make Book.js to create a Book Model.

// Book.js

const mongoose = require(‘mongoose’);

const bookSchema = mongoose.Schema({

  title: {

     type: String,

     require: true

   },

   author: {

      type: String,

      require: true

   },

   numberPages: {

       type: Number,

       require: false

   },

   publisher: {

       type: String,

       require: false

   }

})

const Book = mongoose.model(“book”, bookSchema);
module.exports = Book;

Now we must set up a server for the Book service.

Create a Server for Book Service

Create a file called books.js in the Book folder. We will have different servers for services as we learn to create microservices.

// books.js

require(“dotenv”).config();

const express = require(‘express’);

 

// Connect

require(‘../db/db’);

 

const Book = require(‘./Book’);

 

const app = express();

const port = 3000;

app.use(express.json())

 

app.post(‘/book’, (req, res) => {

    const newBook = new Book({…req.body});

    newBook.save().then(() => {

          res.send(‘New Book added successfully!’)

    }).catch((err) => {

         res.status(500).send(‘Internal Server Error!’);

    })

})

 

app.get(‘/books’, (req, res) => {

   Book.find().then((books) => {

        if (books.length !== 0) {

              res.json(books)

        } else {

            res.status(404).send(‘Books not found’);

       }

    }).catch((err) => {

         res.status(500).send(‘Internal Server Error!’);

    });

})

app.get(‘/book/:id’, (req, res) => {

    Book.findById(req.params.id).then((book) => {

        if (book) {

           res.json(book)

        } else {

            res.status(404).send(‘Books not found’);

        }

     }).catch((err) => {

        res.status(500).send(‘Internal Server Error!’);

    });

})

app.delete(‘/book/:id’, (req, res) => {

    Book.findOneAndRemove(req.params.id).then((book) => {

        if (book) {

             res.json(‘Book deleted Successfully!’)

        } else {

            res.status(404).send(‘Book Not found!’); 

        }

    }).catch((err) => {

         res.status(500).send(‘Internal Server Error!’);

    });

});

app.listen(port, () => {

     console.log(`Up and Running on port ${port} – This is Book service`);
})


Here we have to create a server with express, create the db file necessary for connecting to the database, and utilised the Book model to store data.

There are four routes in Book service:

  • Add books
  • Get all the books from the database
  • Get a particular book
  • Delete a book

Book service needs to be Run at port 3000.

Creating Customer Service

Set up a Customer folder for Customer service, and within that folder, place Customer. JavaScript for model, like we done in the previous part for Book service.

// Customer.js

const mongoose = require(‘mongoose’);

const CustomerSchema = mongoose.Schema({

    name: {

       type: String,

       require: true

    },

    age: {

       type: Number,

       require: true

    },

    address: {

      type: String,

      require: true

    }

})

const Customer = mongoose.model(“customer”, CustomerSchema);

module.exports = Customer;


Now we must set up a server for customer service.

Create a Server for Customer Service

We will also have a dedicated server for customer assistance. Create a file called customer. js.

// customer.js

require(“dotenv”).config();

const express = require(‘express’);

 

// Connect

require(‘../db/db’);

 

const Customer = require(‘./Customer’);

 

const app = express();

const port = 5000;

app.use(express.json())

 

app.post(‘/customer’, (req, res) => {

    const newCustomer = new Customer({…req.body});

    newCustomer.save().then(() => {

       res.send(‘New Customer created successfully!’);

    }).catch((err) => {

        res.status(500).send(‘Internal Server Error!’);

    })

})

app.get(‘/customers’, (req, res) => {

    Customer.find().then((customers) => {

       if (customers) {

          res.json(customers)

       } else {

          res.status(404).send(‘customers not found’);

       }

    }).catch((err) => {

         res.status(500).send(‘Internal Server Error!’);

   });

})

 

app.get(‘/customer/:id’, (req, res) => {

    Customer.findById(req.params.id).then((customer) => {

     if (customer) {

          res.json(customer)

      } else {

          res.status(404).send(‘customer not found’);

      }

    }).catch((err) => {

          res.status(500).send(‘Internal Server Error!’);

   });

})

 

app.delete(‘/customer/:id’, (req, res) => {

Customer.findByIdAndRemove(req.params.id).then((customer) => {

    if (customer) {

         res.json(‘customer deleted Successfully!’)

      } else {

         res.status(404).send(‘Customer Not Found!’);

      }

    }).catch((err) => {

       res.status(500).send(‘Internal Server Error!’);

  });

});

 

app.listen(port, () => {

    console.log(`Up and Running on port ${port}- This is Customer service`);
})


Build the same four customer service routes that we created for the Book service.

Run Customer service at port 5000.

Creating Order Service

For model, create an Order.js file in the Order folder, much like we did for Book and Customer service.

// Order.js

const mongoose = require(‘mongoose’);

const orderSchema = mongoose.Schema({

    customerID: {

       type: mongoose.SchemaTypes.ObjectId,

       require: true

     },

     bookID: {

       type: mongoose.SchemaTypes.ObjectId,

       require: true

     },

     initialDate: {

        type: Date,

        require: true

     },

     deliveryDate: {

        type: Date,

        require: false

     }

})

const Order = mongoose.model(“order”, orderSchema);
module.exports = Order;

Now we must set up a server for the Order service.

Create a Server for Order Service

Inside the Order folder, create order.js.

// order.js

require(“dotenv”).config();

const express = require(‘express’);

const mongoose = require(“mongoose”);

const axios = require(‘axios’);

 

// Connect

require(‘../db/db’);

 

const Order = require(‘./Order’);

const app = express();

const port = 9000;

app.use(express.json())

app.post(‘/order’, (req, res) => {

   const newOrder = new Order({

   customerID: mongoose.Types.ObjectId(req.body.customerID),

   bookID: mongoose.Types.ObjectId(req.body.bookID),

   initialDate: req.body.initialDate,

   deliveryDate: req.body.deliveryDate

});

newOrder.save().then(() => {

   res.send(‘New order added successfully!’)

  }).catch((err) => {

   res.status(500).send(‘Internal Server Error!’);

  })

})

app.get(‘/orders’, (req, res) => {

   Order.find().then((orders) => {

      if (orders) {

          res.json(orders)

       } else {

          res.status(404).send(‘Orders not found’);

       }

   }).catch((err) => {

          res.status(500).send(‘Internal Server Error!’);

   });

})

app.get(‘/order/:id’, (req, res) => {

    Order.findById(req.params.id).then((order) => {

       if (order) {

          axios.get(`http://localhost:5000/customer/${order.customerID}`).then((response) => {

         let orderObject = { 

           CustomerName: response.data.name, 

           BookTitle: ” 

          }

        axios.get(`http://localhost:3000/book/${order.bookID}`).then((response) => {

         orderObject.BookTitle = response.data.title 

         res.json(orderObject);

        })

   })

     } else {

        res.status(404).send(‘Orders not found’);

     }

    }).catch((err) => {

        res.status(500).send(‘Internal Server Error!’);

   });

}) 

app.listen(port, () => {

     console.log(`Up and Running on port ${port} – This is Order service`);
})


Run the customer service at port 9000.

 

In Order service, we will create three routes:

  • Add an order. We have to pass bookId, customerId, initialDate, and deliveryDate for it.
  • Get all the orders from the database
  • Get customers and booking details for a certain order.

To run the final route, ensure that all services are functioning in the background. Since we are receiving information from both book service and customer service.

Conclusion

Every service is independently deployable, scalable, and updatable in microservices which makes microservices an attractive way to build in the industry. Microservices are freely integrated and integrate with other microservices of well-defined systems via protocols such as http, and they remain stable and available in the event of a failure, which means that even if the machine holding the microservice fails, the service must still be provided by the app. We hope your visit to the instructional fulfils the purpose you anticipated. Clone the repository and experiment with the code to create Node.js microservices.

The post How to Build Microservices with Node.js appeared first on Talent500 blog.

]]>
https://talent500.com/blog/how-to-build-microservices-with-node-js/feed/ 0