Let’s build a Blog: Emails, Custom Responses & Nuxt.js 2.0.

Conway
6 min readOct 3, 2018

--

Greetings developers. If you have been following this series, you would have built most of your server-side architecture. We are now ready to start building the front-end of our application. But before we get into that we’ll configure our application to send emails with Mailgun, create Custom Responses & upgrade the frontend of our application to Nuxt.js 2.0.

Table of Contents

First we are going upgrade our frontend to Nuxt.js 2.0 As we have not actually touched our frontend folder its okay to just delete it and start again. In Nuxt.js 2.0 they have added a new scaffolding tool to quickly get your Nuxt application started.

Before we start, make sure that you have NPX installed globally one your machine, if you don’t run npm i npx -g within your terminal. When ready within the root of our project run the following:

npx create-nuxt-app frontend

You will be prompted to set up your project, go ahead and set your own Project name, Project description , whether want to use ESLint, Author Name & to use npm or yarn as your package manager. I have selected Bootstrap as my custom UI Framework as I will be using it to prototype, so its up to you to use one or not! We wont be selecting a server-side framework, we would like the application to be rendered universally and we would like to use the Axios Module. Congratulations your the frontend of your application is powered by Nuxt.js 2.0, we can now finish off our API.

Sending Emails

As we previously installed sails-hook-organics we have access to the Mailgun Helper. Mailgun is an email automation service; with a great API that allows you to send, receive, and track emails. We will be creating email templates using Sails’ Views, to render the emails server-side.

Firstly you need to head to the Mailgun website and sign up for a free account. Once you have signed up you will be presented with a Curl script that contains your sandbox domain and API key, you can also find them on within the Domains page. We now need to add these details to our applications custom configuration config/custom.js, the config file will already contain the mailgunDomain & mailgunSecret properties; so just replace the placeholder values.

We now want to generate a Helper function, this will make it easy for us to select, render & send a specific email template. To do this we need to run sails generate helper send-email. The Helpers have an identical structure to Sails’ Actions, it allows us to define inputs, exits & an async function. Within api/helpers/send-email we need to define Inputs to allow values to be passed into our helper, these will include template for the template name, layout for the main layout of our email, templateData, to for our email recipient and subject for our emails subject.

template: {
description: 'EJS template name',
example: 'password-verify',
type: 'string',
required: true,
},

layout: {
description: 'EJS email layout, false will remove layout entirely',
defaultsTo: 'layout-email',
custom: layout => layout === false || _.isString(layout)
},

templateData: {
description: 'Collection of template data, accessible within EJS template',
type: {},
defaultsTo: {},
},

to: {
description: 'Recipients email address',
type: 'string',
isEmail: true,
required: true,
},

subject: {
description: 'Subject for email',
type: 'string',
defaultsTo: '',
},

Now we need to create the function that will allow us to send the email. We will need to use the Inputs to render the specified Layout & Template into HTML to be passed into the Mailgun Helper, along with the email information and API details.

// Include Node Core modules
const path = require('path');
const url = require('url');
const util = require('util');

// Get the email templates full path
const templatePath = path.join('emails/', inputs.template);

// Get email layout template
let layout = inputs.layout ?
path.relative(path.dirname(templatePath),
path.resolve('layouts/', inputs.layout)) : false;

// Render email HTML
const emailContents = await sails.renderView(
templatePath,
Object.assign({layout, url, util}, inputs.templateData)
);

let {mailgunDomain, mailgunSecret} = sails.config.custom;

// Use Mailgun helper to send email!
await sails.helpers.mailgun.sendHtmlEmail.with({
htmlMessage: emailContents,
to: inputs.to,
from: 'noreply@fullstackedkush.com',
domain: mailgunDomain,
secret: mailgunSecret,
subject: inputs.subject,
testMode: true
});

// All done.
return exits.success();

We have our Helper configured, we now need to create our email views. We start off with our layout, the fileviews/layouts/layout-email.ejs needs to be created. Here we will build a basic HTML email structure, for this I used Foundation for Emails. Once you have your layout you just have to add
<%- body %> where you wish to output the emails content.

The email we will be creating is for the account verification from the create user function. If you remember we generated the verification tokens and their expiry, we need to pass this data into our email. As a side note you will also have to create a Route and configure an Action to modify your Users email status, I have created it for you in the GitHub Repository. Create the file views/emails/verify-account.ejs and add the following:

<p>Greetings, <%= fullName %>!</p>
<p>You have requested an email change, click the link bellow to confirm the change. If not just ignore this!</p>

<!--Create a URL with the token-->
<p>
<a href="<%= url.resolve(sails.config.custom.apiUrl,'/api/v1/email/verify')+ '?token='+ encodeURIComponent(token) %>">Confirm email
</a>
</p>

Now we need to add the Helper function to our create user function, open api/controllers/user/create.js and under where we have set the users session add the following:

// Send email verify email
await sails.helpers.sendEmail.with({
to: newUser.emailAddress,
subject: 'Verify your account!',
template: 'verify-account',
templateData: {
fullName: newUser.fullName,
token: newUser.emailVerifyToken
}
});

Now when a user is created an email will be sent to them with the URL to verify their account. We can now create emails for when a user requests to change an email and for when the user has forgotten their password.

Custom Responses

In Sails we are able to create Custom Responses, with these we are able to modify the way that default responses work or create completely new ones. We are going to create a response to intercept the E_UNIQUE response when a users email isn’t unique. To do this we can run the following command in our terminal sails generate response emailNotUnique, this will create the file api/responses/emailNotUnique.js. Open the emailNotUnique.js and add the following:

module.exports = function emailNotUnique(message) {

const res = this.res;

// Set result message
let result = {
status: 409,
// Set custom message if it is passed into the response
message: message ? message :
'The email address provided is already in use.'
};

// Send JSON as that's what we want!
return res.status(result.status).json(result);

};

Now we are able to add the custom response to our create user actions exits and intercept the E_UNIQUE response. Within user/create.js add the following to the exits property:

emailNotUnique: {
responseType: 'emailNotUnique',
description: 'The email address provided is already in use'
}

And then we need to intercept the response where we are creating our User, before the fetch() function add:

// Intercept the E_UNIQUE response with the emailNotUnique response
.intercept('E_UNIQUE', 'emailNotUnique')

Now if we test the create function with an email that isn’t unique it will return our custom response.

Conclusion

We have now have a functioning API, our next step will be to start building out our front-end. In the next article I will be showing how to build our views with Nuxt.js, I will be building the login & registration views and functionality.

I would recommend pulling the series GitHub Repository as I have commented throughout the code. You can also follow my progress on Instagram and on Twitter.

--

--