Cosmic JS Blog Stay tuned for community news, company announcements and updates from the Cosmic JS team.

How to Build a Simple Blog Using Node.js


In this tutorial I'm going to show you how to create a simple blog using Node.js and Cosmic JS.  This is going to be the fastest and most light-weight blog you have ever created.  Let's get started.

TL;DR

View the demo
Install the Simple Blog App on Cosmic JS
View the codebase on GitHub

Getting Started

Make sure that you have Node.js and NPM installed on your machine, if not, visit the Node.js website to install the latest version.

Make sure you have Yarn installed globally:

npm install yarn -g

Let's start by creating a folder for our app.  In your favorite terminal run the following commands:

mkdir simple-blog
cd simple-blog

Now let's add a package.json file to import all of our dependencies for our app:

vim package.json

Add the following to our package.json file:

{
  "dependencies": {
    "cosmicjs": "^2.39.0",
    "express": "^4.15.2",
    "hogan-express": "^0.5.2",
    "nodemon": "^1.11.0"
  },
  "scripts": {
    "start": "node app.js",
    "development": "nodemon app.js"
  }
}

 It's a pretty light dependency list for a pretty light app.  So what we will install is:

1. The Cosmic JS Node Module to get our content from our Cosmic JS Bucket.
2. Express for our web app framework
3. Hogan for our template views
4. Nodemon for development

Our scripts are necessary for starting our app in production and development.

Run the following command to install our dependencies:

yarn

Building Our Blog

Next, let's begin building our blog pages.  Create a file titled app.js:

vim app.js

and add the following to app.js:

const express = require('express')
const app = express()
const hogan = require('hogan-express')
const http_module = require('http')
const http = http_module.Server(app)
app.engine('html', hogan)
app.set('port', (process.env.PORT || 3000))
app.use('/', express.static(__dirname + '/public/'))
const Cosmic = require('cosmicjs')
const helpers = require('./helpers')
const bucket_slug = process.env.COSMIC_BUCKET || 'simple-blog-website'
const read_key = process.env.COSMIC_READ_KEY
const partials = {
  header: 'partials/header',
  footer: 'partials/footer'
}
app.use('/', (req, res, next) => {
  res.locals.year = new Date().getFullYear()
  next()
})
// Home
app.get('/', (req, res) => {
  Cosmic.getObjects({ bucket: { slug: bucket_slug, read_key: read_key } }, (err, response) => {
    const cosmic = response
    if (cosmic.objects.type.posts) {
      cosmic.objects.type.posts.forEach(post => {
        const friendly_date = helpers.friendlyDate(new Date(post.created_at))
        post.friendly_date = friendly_date.month + ' ' + friendly_date.date
      })
    } else {
      cosmic.no_posts = true
    }
    res.locals.cosmic = cosmic
    res.render('index.html', { partials })
  })
})
http.listen(app.get('port'), () => {
  console.info('==> 🌎  Go to http://localhost:%s', app.get('port'));
})

There are a few things happening here:

1. We are importing our essential modules: Express, Cosmic JS, setting our PORT dynamically, etc.
2. We are pointing to some partials: header and footer, you can reference these partials from the codebase on GitHub.
3. We view our app home page ('/') and query our Cosmic JS Bucket for Post Objects, set the friendly date, then return the index.html template.
4. We are also adding our data to this page in the form of a global data store: cosmic.  This data structure makes our template implementation super intuitive.

Adding Our Home Page Template Variables

This part of the process is the most fun because it shows you the power of Cosmic JS combined with a declarative, logic-less template system like Mustache.  Let's create a folder called views and add our index.html file:

mkdir views
cd views
vim index.html

Add the following to index.html:

{{> header }}
  <main class="container">
    {{# cosmic.objects.type.posts }}
      <div class="card" data-href="/{{ slug }}">
        {{# metadata.hero.imgix_url }}
          <div class="blog-post-hero blog-post-hero--short" style="background-image: url({{ metadata.hero.imgix_url }})"></div>
        {{/ metadata.hero.imgix_url }}
        <div class="card-padding">
          <h2 class="blog__title blog__title--small">
            <a href="/{{ slug }}">{{ title }}</a>
          </h2>
          <div class="blog__author">
            <div class="blog__author-image" style="background-image: url({{ metadata.author.metadata.image.imgix_url }}?w=100)"></div>
            <div class="blog__author-title">by <a href="/author/{{ metadata.author.slug }}">{{ metadata.author.title }}</a> on {{ friendly_date }}</div>
            <div class="clearfix"></div>
          </div>
          <div class="blog__teaser droid">{{{ metadata.teaser }}}</div>
          <div class="blog__read-more">
            <a href="/{{ slug }}">Read more...</a>
          </div>
        </div>
      </div>  
    {{/ cosmic.objects.type.posts }}
  </main>
{{> footer }}

What's happening here?
1. We pull in our header file with the Mustache template variable.
2. We pull in our Cosmic data using the Mustache variable {{ cosmic }} which has everything we need to layout our page's dynamic data.
3. We are looping through our {{ cosmic.objects.type.posts }} and rolling out our blog posts.

What I like about this approach is that the template is completely logic-less aside from some boolean queries and array looping.  It really does a great job of keeping our logic separate from our presentation (thanks Chris Wanstrath!)

If you want to build out the rest of the application, clone the GitHub repo and follow the README instructions.

Conclusion

This is the abridged version of the Simple Blog app available for download in the Cosmic JS Apps page.  The full codebase includes a single post page view as well as a page dedicated to each author's posts.  View the full codebase on GitHub and deploy this app in a few clicks from your Cosmic JS dashboard by installing the app to your Cosmic JS Bucket.

I hope you enjoyed this tutorial, if you have any questions reach out to us on Twitter and join our community on Slack.

You may also like


Brand Managers manage, well, brands.  Seems simple enough right?  It does in title and theory alone.  Managing a brand means managing the brand’s tone, voice, messaging, consumer segmentation, price points, marketing, advertising and all of the subsequent elements and assets that fall out of such an engagement.  Having managed brands for years myself, I can attest to the magnitude of the job at hand.  Once the client has agreed upon a general direction, it becomes the brand manager’s responsibility to ignite passion and results from the internal agency team that services the account.  As my workload would increase month over month as business heated up or an account was grown, I went through the whole Automation | Delegation | Elimination routine to see what I could cut out of my schedule as busy work.  The problem?  I was only one person.  I could only affect hours tallies on my end, but had little to no influence over design, development, copywriting & production. 


The area that always seemed to be the weak link in terms of staying on budget was in development.  Boutique agencies struggle to attract qualified talent with their long work hours and subpar compensation, and then after taking a gamble on a more junior talent that is developed over time, retention is a beating.  Companies line up with development jobs that pay 2X, sometimes 3X what a boutique agency is willing to part with for that developer’s compensation package.  This is all before taking into account staging servers, hosting servers, CMS logins, local installations of CMS systems and all of the red tape and bureaucracy associated that can bog down a productive workflow.  As a result, my quotes back to clients for websites, microsite, landing pages and applications were always a bit higher than they were expecting.  I started searching for a cloud-based solution to my CMS woes to cut out some of the middle men and see if there was an easier way to 'get this digital property live'. 

I found 
Cosmic JS.  Had I been told as a Brand Manager that I could eliminate the local CMS, the hosting server and the shared logins of content editing, I would have seen the value immediately.  No longer having to build APIs on a per-CMS / per-client basis, no longer having to build out a proprietary backend, yet still attaining the same custom-value would have been a lifesaver and a half for a brand manager focused on the bottom line.  It would have easily cut my back end developers’ hours estimates by 40%, eliminated costly hosting servers and would have streamlined content-centric employees within the agency to not have to deal with the red tape of updating content within a traditional CMS. 

Whether we picked out a
content-ready application or plugged GitHub into Cosmic JS, I’m seeing time and cost savings at every turn.  Music to a brand manager’s ears, and music to a boutique agency’s margin and bottom line.  As it turns out, it also benefits the client as their content is put first, their content is pushed live more quickly and is devourable globally on any device.

In this installment of the Cosmic JS Developer Spotlight Series, we sat down with Rick Hanlon, a Front End Engineer  and recent New Yorker that is now residing in London, England working on the front end team at Facebook. Rick is also on the core team of Jest, a JavaScript testing platform. Follow Rick on Twitter or LinkedIn and enjoy the Q/A.

Cosmic JS has an understandable hierarchy for content management and can be used as a stand-alone content organizer while a website is being built. Buckets, Object Types, Metafields and Files can act as a sitemap or content portal for a team wanting to organize information more effectively during the development process.  And when the site is ready for development and launch, the API is ready to begin delivering the pre-populated content saving time and money.

You can now use Cosmic JS to deploy your GitHub private repos to the web.  All you have to do is sign up or sign in using your GitHub account and authorize access to your private repos. (Don't worry, we only access your private repos when you are ready to deploy them to the web).


After you authorize access the process is super easy.  Just go to Your Bucket > Settings > Deploy Web App and choose which private (or public) GitHub repo you would like to deploy. You can also deploy an app from any public Git repo url (make sure your app follows the Heroku deployment guidelines).


Click Deploy Web App and your private repo will be deployed to the world!

In our latest installment of the Cosmic JS Developer Spotlight Series, we sat down with Matt Cain, a physics major turned Creative Director and Developer. 

Cosmic JS is a powerful CMS API that allows you to manage content for your websites and applications faster and easier.  But did you know that you can also use Cosmic JS to deploy code to your website (in any language) from any GitHub repository?  In addition to deploying content and code, starting today you can also add unlimited domains to your deployed application.  This is revolutionary because it means that moving forward all you need to launch your website is a git repository, a domain name provider and Cosmic JS!  No more hosting server necessary!  I’ve added a couple of screencasts for your viewing.  Let’s get started.

Create a Bucket

After logging in to your Cosmic JS account, create a new bucket.  After creating your new bucket, you will be prompted to install an app.

Install an App

Let's go ahead and install an app, but you could just as easily skip this step and deploy your own application pointed to your Cosmic JS bucket.  After installing your app, you will be prompted to deploy the application.

Deploy the App

Next click "Deploy Web App" to launch the web application to http://[your-bucket-slug].cosmicapp.co.  Once you do this it will take about a minute for the application to deploy on a custom instance of the Cosmic JS app server.  While this is working its magic, let's add our custom domains…

Add Custom Domains

The Cosmic app server subdomain is great for development and staging, but when you go live, you're going to want to add our own custom domains.  Cosmic JS makes this incredibly easy by providing the option to add custom domains to your deployed application.  Here are the 4 easy steps:

1. Go to Settings > Deploy Web App > Add Custom Domains (upgrade your account if needed)
2. Add your custom domains
3. Click "Set Domains"
4. Go to your domain name registrar's website and point your A Name Records to the Cosmic JS app server located at 162.243.13.186

Now navigate to your domain and notice that you now have your application hosted at your custom domain!  Add as many domains / subdomains as you need!  Whenever you need to deploy changes to the app, just push the changes up to your GitHub repository and click "Redeploy Web App".

Cosmic JS now gives you the power to deploy a website faster and more nimbly than any other system.  And all you need is a git repository, a domain name provider and Cosmic JS!