Getting the Client’s Local Time in Node.js

I have my first node.js/express app hosted on Heroku and found it quite easy to work with. One thing that initially tripped me up was how to run JavaScript on the client side. As you may know, node.js runs JavaScript on the server, with many advantages. But some scripts you need to run on the client, like getting the client’s timezone, which was my requirement. If I used natively in a view, it would give me the server timezone, because that’s where the script would be run.

To get the client’s timezone, I had to serve up some static files, which express allows with the .static method. E.g.:

app.use(express.static(path.join(__dirname, 'public')));

My static JavaScript files are organized as so:

  • In a public folder, a single file “myApp.js” imports all needed functions from other static JavaScript files and runs them where needed. E.g.:
import setTimezone from './modules/getTimezone';

setTimezone( $('#timezone') );

where ./modules/getTimezone.js looks like:

import moment from 'moment';
import tz from 'moment-timezone';

function setTimezone(timezoneEl) {
  timezoneEl.value =;

export default setTimezone;
  • myApp.js is compiled into App.bundle.js by webpack via a webpack.config.js file that looks something like:
const path = require('path');
const webpack = require('webpack');

const config = {
  entry: {
    App: './public/javascripts/myApp.js'
  output: {
    path: path.resolve(__dirname, 'public', 'dist'),
    filename: '[name].bundle.js'
  module: {
    rules: [javascript]

module.exports = config;
  • The resulting output file is then referenced on the layout page (pug):
block scripts

It’s very easy to add additional static scripts once you’ve done the setup once. Fun!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s