Sessions in express.js

Using cookies in express can seem like a daunting task. The following is a basic demonstration of how to install sessions using express.js. This blog post will not dive into all of the cool things that sessions allow you to do but it will get you started, to the point where you can play around with the session object throughout the basic architecture of a site.

Note if you are running this example code you will need the following require statments:

var express = require('express'),
    http = require('http'),
    uuid = require('node-uuid'); //to install this package run sudo npm install node-uuid from the command line

The first step to adding sessions to your site is enabling express’s cookie parsing middleware. You’ll add a statement to your app.configure declarations (see below). You will also need to use express.cookieSession.

app.configure(function() {
  app.set('port', 8080);
  app.set('views', __dirname + '/views');
  app.use(express.cookieParser());
  app.use(express.cookieSession({ secret: 'secret'}));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

Adding the code above, will allow you to make use of a cookie object as the user navigates your site. This object looks like this:

{ cookie: 
  { path: '/',
    _expires: null,
    originalMaxAge: null,
    httpOnly: true }
}

You can set the max age property to a number of milliseconds, however long you want so that you can remember the user. Note there limitations to how long oyu can remember a user but these are generally dictated by browsers.

If you want to see the session in use, I suggest you add the following code to your server to get a sense of how you can play around with the object based on various requests.

app.get('/test', function(req, res){
  req.session.sessionID = uuid.v1();
  res.send('To see your session ID *Click Here*)
});

app.get('/', function(req, res){
  res.send(req.session.sessionID);
});

//note the click here portion should be a closed html a tag - for some reason it doesnt work in tumblr's html editior within the pre

These GET handlers will provide you with an interface to play around with the cookieSession object. When you visit ‘/test’ you will generate a sessionID that I have namespaced to the session object. When you follow this initial request up with a GET request to ‘/’ the sessionID will be sent as a response. While this is a somewhat naive demonstration it does show how you can store information on the session object as the user travels around your site. This is especially helpfull when build multi-page apps like an e-commerce application where the user navigates the site with a shopping cart.

FlixGuru

flixGURU

Over the course of six days at Hack Reactor I worked on a personal project that I dubbed flixGURU. The goal of the project was to provide users with a visual representation of the box office based on the top 35 grossing movies each week. For the project I used d3 and the rotten tomatoes API. Let me know what you think.

I have included the project’s readme below.

flixGURU

=========

flixGURU is a d3 project that graphs the top 35 movies at the box office based on their aggregate critical score.

  • The project uses the Rotten Tomatoes API as its data source for the box office rankings, movie review data, movie poster images, and other movie related information
  • The d3 code is based on the Vishna project. I adapted and refactored the code from this project to fit this application’s needs.

API Call

http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?APIKEY&limit=36&callback=?"

Bubbles Size

d.score refers to the aggregate critical score of each movie. I begin the range at 30 so that low scoring movies are visible and cap it at 75 to manage the scale of the entire infographic.

r = d3.scale.linear()
    .domain([ d3.min(posts, function(d) { return d.score; }),
            d3.max(posts, function(d) { return d.score; }) ])
    .range([ 30, 75 ])
    .clamp(true);

Appending the rank to each bubble

d.text = svg.append("text")
            .attr("x", d.x + (.2 * d.r))
            .attr("y", d.y - (.2 * d.r))
            .text(d.rank)
            .attr("font-size", "34px")
            .attr("font-family", '"Amatic SC", cursive')
            .attr("text-align", "left")
});

Best Practices: Programming Variables

The art of creating variable names in computer programming is very simple; be as literal as possible without being overly verbose. Unlike mathematics, where the greek alphabet was required to give mathematicians more single character variables, programmers take pride in creating descriptive variable names.

YIKES!

Programmers strive to write code that is elegant and legible to benefit other humans not to benefit the computer. As such, there are certain conventions that one must follow if they plan on showing other developers their code. Perhaps the most important of these is whitespace, but that is a topic for another post. Second on my list of important style habits is the practice of creating good variable names. The code below provides examples of good naming practices, please let me know if you have any comments or questions.

Creating A Dev Environment From Scratch

image

I bought a new 13” MacBook Air today! I am going to walk you through every step of setting up a my full stack javascript development environment.

Chrome

After the initial hardware setup, I opened Safari (probably for the last time) to initiate download for Google Chrome. Chrome is my preferred browser largely because it comes packaged with amazing developer tools and a javascript console. That being said, I will probably also download Firefox because it also has some neat to tools (e.g. the 3D element view) but Chrome will be the browser that I will use 90% of the time. 

Sublime

Moving on to my editor, I work in Sublime. It is great as far non-unix style text editors go and has tons of neat short cuts to cut down on typing. When installing sublime you are going to want to install the command line shortcut so that you can launch entire directories from terminal (instructions here).

X Code

To be honest I never open X Code. I have but I love the chrome debugger and have no use for it as a debugging tool. Nonetheless, it is required for the node debugger and other packages (so I hear). This is a big file, greater than 1gb, so it is good to get the download out of the way.

HomeBrew

HomeBrew is the best package manager available. It should be installed from the command line. Instructions are available here.

node.js

Node is awesome because server side javascript is awesome. The installation is very easy as installing from source is no longer required. You wil also want to install the node debugger but I will save that for a later post.

Git

In order to run git commands from terminal one needs to download the latest version of git here. Note that in order to properly install git you may need to make a change in your computer’s System Preferences. In your Security & Privacy preferences set the Allow applications downloaded from:  to Anywhere.After changing this setting you can install git commands from source or by utilizing the installer.

Hoisting

Part of our daily routine at Hack Reactor includes completing one or two interview style questions every morning before we resume the broader lesson. Today, we were asked about an oddity in Javascript known as hoisting. Specifically, what code can we add below line 1 that will result in the program not returning undefined? 

The term hoisting refers to the Javascript’s practice of bringing var and function declarations to the top of the code block. As such, the code implementation (beginning on line 5) below results in an interpretation (beginning on line 13) that alerts “bar”.

If you want to learn more about hoisting and other quirks of Javascript, I recommend that you visit Javascript Garden. This is a great reference tool that I find myself using on a daily basis.