DEV Community

Tonware-emi
Tonware-emi

Posted on • Updated on

How to use nhost serverless functions with javascript

Nhost logo
Good day everyone, today we are going to build an email sending api with nhost serverless functions, nhost is a firebase alternative which you should check out, they provide stuff like a postgreSql database, cloud storage and so much more, now lets jump right in to the code, but first let create a new project and install nodemailer and express , also note that inorder for you to do this you got to have node.js installed on your computer, if your new to serverless functions just know that they are programs (files or functions), that are hosted on servers that are maintained by cloud provider, so you don't really need to know about cloud computing in other to have a working backend server but i advice that you at least have some basic knowledge of cloud computing if your doing programing professionally.
ok now lets start, first open your terminal and type

mkdir emailer
Enter fullscreen mode Exit fullscreen mode

to make a folder for the project

cd email-sender
Enter fullscreen mode Exit fullscreen mode

to enter the folder

npm init -y
npm i -d nodemailer express
Enter fullscreen mode Exit fullscreen mode

To initialize the project and install the required dependencies
now we just need two files to start coding. first type

mkdir functions
Enter fullscreen mode Exit fullscreen mode

to make a folder called functions, the reason we need this folder is cause only javascript or typescript files made in this specific folder will be used as api routes which we will make request to run the backend code.
now in the functions folder make a file called email.js for linux and mac type

touch email.js
Enter fullscreen mode Exit fullscreen mode

while for windows type

type nul > email.js
Enter fullscreen mode Exit fullscreen mode

you can name the file what ever you want but just note that the name of the file will be part of your api route. now the second file that we need is test.js file which we will use to test the api this should be in the root folder.
open the email.js file in a text editor and type


var nodemailer = required("nodemailer");

export default (req, res)=>{
res.status(200).send({response: "hello world"});
}
Enter fullscreen mode Exit fullscreen mode

Now we need to create a git repository, signup in nhost.io and add that repository as a project. this should be easy as nhost is very user friendly, go to functions page in the site and then you should see this email.js file as an api route in there and the base url at the bottom of the page, if you didn't then the deploy most likely failed or you missed a step. now open the test.js file and make a fetch request to the api route. then add what ever you named the file at the end, in my case i will add email. it should look like this

fetch("https://{project-url}.nhost.run/v1/functions/{name-of-file:eg_email}").then(data => data.json())
.then(response => console.log(response));

Enter fullscreen mode Exit fullscreen mode

mine is

fetch("https://wgtebtfqvnppecpnpkab.nhost.run/v1/functions/email").then(data => data.json()).then(response => console.log(response));

//output
/* {
  response:"hello world"
}
*/

Enter fullscreen mode Exit fullscreen mode

If that all went well then lets move to the next step. Now we are going to send a post request and get a response after processing the request. you can send anything but am just going to send "Hello world"

fetch("https://wgtebtfqvnppecpnpkab.nhost.run/v1/functions/email", {
    method: "POST",
    body: JSON.stringify({
    req:"Hello world"
    }),
    headers: {
        "Content-Type": "application/json"
    }
})
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error))
Enter fullscreen mode Exit fullscreen mode

Now in the email.js we will access and send the request as a response.

export default (req,res) =>{
res.status(200).send(JSON.parse(req);
}
Enter fullscreen mode Exit fullscreen mode

Now if that all went well let's send an email with nhost servers less functions we are going to send an email using nodemailer,
if you don't know how to use nodemailer you can check it out here https://www.w3schools.com/nodejs/nodejs_email.asp

nodemailer in serversless function example

var nodemailer = require('nodemailer')
var express = require("express")


export default (req, res) => {
var request = JSON.parse(req)
var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: request.sender
    pass: request.password
  }
});

var mailOptions = {
  from: request.sender,
  to: request.reciever,
  subject: request.title,
  html: request.html
};



  transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    res.status(200).send({
      err:error,
      username: request.sender,
      password: request.password
    })
  } else {
    console.log('Email sent: ' + info.response);
    res.status(200).send({
      response: "email has been sent"
    })
  }
});

}
Enter fullscreen mode Exit fullscreen mode

You might have noticed that I used replace function after turing the req to json form cause originally the req parameter was in it's object string form, then the Json stringify function changes the object to a json and addes an extra double quote cause its in json format.

congrats you sent an email with JavaScript in the nhost serversless function
you can see the code in my git repository
https://github.com/tonwareemi/emailer

Top comments (0)