Generate Fake Data for Your JavaScript Applications Using Faker

Free Course

Build Your First Node.js Website

Node is a powerful tool to get JavaScript on the server. Use Node to build a great website.

Introduction

When building out applications, we will often need data to show off how it works. It won’t be much of an application if all our tables are blank!

Often, when we first start building out an application, we don’t want to worry too much about the data. Having to create a database and fill it with sample data like users is an annoying step that is just in the way of creating an amazing app.

Luckily Marak has created a neat package that lets us create fake data on the fly: faker.

A Quick Faker Example

Let’s say we wanted to create a user on the fly.

We want this user to have a name, email, address, bio, and even an image.

In Node, all we would have to do is:


var user = {
  name: faker.name.findName(),
  email: faker.internet.email(),
  address: faker.address.streetAddress(),
  bio: faker.lorem.sentence(),
  image: faker.image.avatar()
};

Just like that, we have a whole user object that we can use within our application! The above will spit out:


{
  "name": "Adaline Carroll",
  "email": "Albina.Ledner@gmail.com",
  "address": "545 Fritsch Locks",
  "bio": "dolorem officiis doloribus ut",
  "image": "https://s3.amazonaws.com/uifaces/faces/twitter/joelhelin/128.jpg"
}

Now we have a user and can move along with our application. No need to fuss about the database or populating it with fake users!

Let’s learn a bit more about how to use this helpful package.

Using Faker

You can use faker from within your browser or on the server with Node.

From the docs, the installation instructions for both browser and Node are:

Browser


  <!-- LOAD FAKER -->
  <script src="faker.js">

  <script>
    var name = faker.name.findName();
    var randomEmail = faker.internet.email();
  </script>

Node


  var faker = require('faker');

  var name = faker.name.findName();
  var randomEmail = faker.internet.email();

Super easy stuff. Let’s run through the list of items that we can pull.

Faker Data

There is a huge amount of data that is able to be pulled. The overall category list is:

  • name
  • address
  • phone
  • internet
  • company
  • image
  • lorem
  • helpers
  • date
  • random
  • hacker

Each of those categories has a giant amount of options within itself. We won’t go through them all, but an example is that for the name category, the following are available:

  • name
    • firstName
    • lastName
    • findName
    • prefix
    • suffix

Each of these are accessible as a function. For instance:


  // Chris
  var firstName = faker.name.firstName();

  // Sevilleja
  var lastName = faker.name.lastName();

  // Chris Sevilleja
  var findName = faker.name.findName();

  // Mr.
  var prefix = faker.name.prefix();

  // PhD
  var suffix = faker.name.suffix();

For a giant list of all the calls that are available through faker, check out the API.

Helpers

In addition to the many categories provided, faker also gives access to helpers. These are meant to make pulling data easier. Instead of picking one field here or there, these helpers can give a large amount of data that one would typically use in an application.

Here we’ll give examples of the main helpers that are usable in our own applications:

fakers.helpers.contextualCard()

A user card that contains name, username, avatar, email, and address.


{
  "name": "Kaleigh",
  "username": "Kaleigh60",
  "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/mbilderbach/128.jpg",
  "email": "Kaleigh6047@gmail.com",
  "dob": "1961-08-07T02:37:45.068Z",
  "phone": "113.601.0680",
  "address": {
    "street": "Myah Course",
    "suite": "Apt. 657",
    "city": "Boyerberg",
    "zipcode": "66413-8920",
    "geo": {
      "lat": "-44.6203",
      "lng": "16.7454"
    }
  },
  "website": "megane.biz",
  "company": {
    "name": "Little-Reinger",
    "catchPhrase": "Enhanced regional emulation",
    "bs": "interactive generate bandwidth"
  }
}

fakers.helpers.userCard()

A smaller card with less user information. This one doesn’t come with a user avatar.


{
  "name": "George Kohler",
  "username": "Emilio_Grady49",
  "email": "Aurore_Wintheiser90@gmail.com",
  "address": {
    "street": "Corwin Cove",
    "suite": "Suite 550",
    "city": "New Myah",
    "zipcode": "57817",
    "geo": {
      "lat": "-3.4045",
      "lng": "-16.7806"
    }
  },
  "phone": "1-806-338-0724 x844",
  "website": "katheryn.net",
  "company": {
    "name": "Purdy, Lesch and Jacobi",
    "catchPhrase": "Programmable incremental frame",
    "bs": "24/365 optimize initiatives"
  }
}

fakers.helpers.createTransaction()


{
  "amount": "757.24",
  "date": "2012-02-02T08:00:00.000Z",
  "business": "Bahringer Group",
  "name": "Home Loan Account 5279",
  "type": "deposit",
  "account": "63843216"
}

faker.helpers.createCard()

The full might of the user card along with a section called posts that could help simulate blog articles.


{
  "name": "Fern Ritchie",
  "username": "Vladimir.Feest",
  "email": "Llewellyn_Robel@gmail.com",
  "address": {
    "streetA": "Ratke Street",
    "streetB": "431 Terry Prairie",
    "streetC": "027 Tyler Plaza Apt. 166",
    "streetD": "Apt. 095",
    "city": "Crooksstad",
    "state": "New Hampshire",
    "country": "Ukraine",
    "zipcode": "53303",
    "geo": {
      "lat": "-5.9355",
      "lng": "20.5942"
    }
  },
  "phone": "477-849-4756 x71564",
  "website": "emile.org",
  "company": {
    "name": "Stehr Inc",
    "catchPhrase": "Universal 6th generation contingency",
    "bs": "granular whiteboard bandwidth"
  },
  "posts": [{
    "words": ["voluptatem", "quia", "ipsam"],
    "sentence": "maxime et nemo et sed",
    "sentences": "blanditiis sint molestiae facilisnet molestiae velit consequatur sit aut iure nihilneaque quo voluptatibus",
    "paragraph": "reiciendis exercitationem assumenda provident odionasperiores fugit officianperferendis exercitationem annam et eana ex autem ducimusnsint tenetur officia ratione nesciunt impedit qui"
  }, {
    "words": ["voluptatem", "fugiat", "laborum"],
    "sentence": "quis vel consequatur placeat eum voluptas laboriosam",
    "sentences": "natus ut assumenda esse rerum repudiandaentempore excepturi nemo et velit inventore minus nihil officiisnexcepturi corrupti enim explicabo quaerat",
    "paragraph": "sint eum tenetur id occaecatinitaque veritatis aperiam libero quibusdam repudiandae explicabo accusamus rerum inventorenet placeat enimndolor sit dolores nulla doloribus"
  }, {
    "words": ["illum", "quia", "voluptas"],
    "sentence": "libero eos quia velit qui sint aut",
    "sentences": "eligendi esse blanditiis magni perferendis cumque quibusdam qui iste vitaenaliquam odio aut quaeratnveritatis consequatur qui consequuntur",
    "paragraph": "qui facere ex et consequaturnut iusto maxime quia deleniti sint autnut inventore magni ipsum necessitatibus et numquam qui consectetur aperiamnnam non quisquam tempore corporis adipisci nobis remnqui doloribus inventore itaque est corrupti modi vero quidem quaerat"
  }],
  "accountHistory": [{
    "amount": "435.13",
    "date": "2012-02-02T08:00:00.000Z",
    "business": "Dare Inc",
    "name": "Home Loan Account 4225",
    "type": "payment",
    "account": "69883581"
  }, {
    "amount": "993.77",
    "date": "2012-02-02T08:00:00.000Z",
    "business": "Yundt, VonRueden and Marks",
    "name": "Credit Card Account 2737",
    "type": "withdrawal",
    "account": "32957725"
  }, {
    "amount": "844.46",
    "date": "2012-02-02T08:00:00.000Z",
    "business": "Sipes-Boyer",
    "name": "Investment Account 5882",
    "type": "deposit",
    "account": "50708763"
  }]
}

Using in a Sample Node API

We can create a quick Node API that returns fake data. As an example, if we wanted an API endpoint ot return user data, we can create:


app.get('/api/user', function(req, res) {
  res.json({
    name: faker.name.findName(),
    email: faker.internet.email(),
    address: faker.address.streetAddress(),
    bio: faker.lorem.sentence(),
    image: faker.image.avatar()
  };
});

When our server is started, we can see this API endpoint when we use POSTman to see our data come back in JSON form.

node-faker-sample

Conclusion

Hopefully this package will help you in your JavaScript development. This package helps to easily mock an API and return user information. You can get creative with it and even use this package for financial transactions.

I would encourage you to take a look at the faker homepage as well which helps you visualize the amount of data that comes out of this package.

Chris Sevilleja

Co-founder of Scotch.io. Slapping the keyboard until something good happens.