Node.Js

Jun 2016

Sending emails from Ghost with Nodemailer and SparkPost

While I personally prefer Jekyll to Ghost in the battle of minimalistic CMS platforms, I recently set up a Ghost blog for work and connected the built-in Nodemailer email module with SparkPost, an email service. Here’s how:

  1. Set up a SparkPost account and verify your sending domain.
  2. Go to SparkPost Accounts –> SMTP Relay and copy the host, port and username.
  3. Under Accounts –> API Keys, select the Send via SMTP permission and generate a new API key. The generated API key will be your SMTP password.
  4. Open up your Ghost blog’s config.js, and modify the production section.
  production: {
    url: 'https://example.com/blog',
    mail: {
      from: '"Example.com Blog" <no-reply@example.com>',
      transport: 'SMTP',
      options: {
        host: 'smtp.sparkpostmail.com',
        port: 587,
        auth: {
          user: 'SPARKPOST_SMTP_USERNAME',
          pass: 'SPARKPOST_SMTP_API_KEY'
        }
      }
    },
    database: {
    ....
    }
  }

You can test your configuration by inviting someone to your Ghost installation. The invitee should receive an email from Example.com blog.

May 2016

Setting up CORS with pre-flight request handling for development use in Node + Express

“Cross-Origin Resource Sharing” (CORS)-related errors are a common occurrence while developing a site with a separate frontend and API backend. While the cors module can set headers and respond to pre-flight requests, I didn’t find any documentation to set it up only in the Node development environment (assuming you don’t want to expose your APIs to requests from multiple domains).

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

if (app.get('env') === 'development') {
  console.log('Enabling CORS');
  app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With'); //Add other headers used in your requests

    if ('OPTIONS' == req.method) {
      res.sendStatus(200);
    } else {
      next();
    }
  });
}

//Set up express routes here

This enables CORS for all Express routes and responds to pre-flight OPTIONS requests with HTTP status OK (200) only during development. If you haven’t already set your NODE_ENV to development, you can do so and start your server like so

NODE_ENV=development node index.js