File: README.md
โก๏ธ Try it Online
๐ API Documentation
โ ๏ธ You are reading the docs for the [next](https://github.com/faker-js/faker/tree/next) branch โ ๏ธ
Please proceed to the Getting Started Guide for the stable release of Faker.
For detailed API documentation, please select the version of the documentation you are looking for.
| Version | Website |
|---|---|
| v10 (next) | https://next.fakerjs.dev/ |
| v10 (stable) | https://fakerjs.dev/ |
| v9 (old) | https://v9.fakerjs.dev/ |
๐ Features
- ๐ง Person - Generate Names, Genders, Bios, Job titles, and more.
- ๐ Location - Generate Addresses, Zip Codes, Street Names, States, and Countries!
- โฐ Date - Past, present, future, recent, soon... whenever!
- ๐ธ Finance - Create stubbed out Account Details, Transactions, and Crypto Addresses.
- ๐ Commerce - Generate Prices, Product Names, Adjectives, and Descriptions.
- ๐พ Hacker - โTry to reboot the SQL bus, maybe it will bypass the virtual application!โ
- ๐ข Number and String - Of course, we can also generate random numbers and strings.
- ๐ Localization - Pick from over 70 locales to generate realistic looking Names, Addresses, and Phone Numbers.
Note: Faker tries to generate realistic data and not obvious fake data.
The generated names, addresses, emails, phone numbers, and/or other data might be coincidentally valid information.
Please do not send any of your messages/calls to them from your test setup.
๐ฆ Install
npm install --save-dev @faker-js/faker๐ช Usage
// ESM
import { faker } from '@faker-js/faker';
// CJS
const { faker } = require('@faker-js/faker');
export function createRandomUser() {
return {
userId: faker.string.uuid(),
username: faker.internet.username(),
email: faker.internet.email(),
avatar: faker.image.avatar(),
password: faker.internet.password(),
birthdate: faker.date.birthdate(),
registeredAt: faker.date.past(),
};
}
export const users = faker.helpers.multiple(createRandomUser, {
count: 5,
});๐ Modules
An in-depth overview of the API methods is available in the documentation for v10 (stable) and v10.* (next).
Templates
Faker contains a generator method faker.helpers.fake for combining faker API methods using a mustache string format.
console.log(
faker.helpers.fake(
'Hello {{person.prefix}} {{person.lastName}}, how are you today?'
)
);๐ Localization
Faker has support for multiple locales.
The main faker instance uses the English locale.
But you can also import instances using other locales.
// ESM
import { fakerDE as faker } from '@faker-js/faker';
// CJS
const { fakerDE: faker } = require('@faker-js/faker');See our documentation for a list of provided languages.
Please note: Not every locale provides data for every module. In our pre-made faker instances,
we fall back to English in such a case as this is the most complete and most commonly used language.
If you don't want that or prefer a different fallback, you can also build your own instances.
import { de, de_CH, Faker } from '@faker-js/faker';
export const faker = new Faker({
locale: [de_CH, de],
});โ๏ธ Setting a randomness seed
If you want consistent results, you can set your own seed. If you are using faker.date methods, there are additional considerations. See Reproducible Results.
faker.seed(123);
const firstRandom = faker.number.int();
// Setting the seed again resets the sequence.
faker.seed(123);
const secondRandom = faker.number.int();
console.log(firstRandom === secondRandom);๐ค Sponsors
Faker is an MIT-licensed open source project with its ongoing development made possible entirely by the support of these awesome backers
Sponsors
Backers
โจ Contributing
Please make sure to read the Contributing Guide before making a pull request.
๐ Credits
Thanks to all the people who already contributed to Faker!
The fakerjs.dev website is generously hosted by Netlify, with search functionality powered by Algolia.
๐ Changelog
Detailed changes for each release are documented in the release notes.
๐ What happened to the original faker.js?
Read the team update (January 14th, 2022).
๐ License
File: docs/guide/frameworks.md
Frameworks
Faker can easily be used with a variety of testing frameworks. Here are a few examples with popular frameworks.
Note that these examples use only the en locale for better performance. For more information visit localization.
Vitest and Jest
Since Vitest and Jest use an extremely similar notation, this section will cover both at once.
The main difference is that testing methods need to be imported in Vitest.
Simply crop that line out for a Jest integration.
These frameworks work about exactly as you would expect with Faker. Here's a minimal example:
import { faker } from '@faker-js/faker/locale/en';
import { describe, expect, it } from 'vitest';
describe('reverse array', () => {
it('should reverse the array', () => {
const title = faker.person.jobTitle();
const name = faker.person.fullName();
const animal = faker.animal.bear();
const array = [title, name, animal];
expect(array.reverse()).toStrictEqual([animal, name, title]);
});
});It can sometimes be useful to do seeded tests, where we seed our faker instance with a static value so that it will generate the same random value each time.
These are especially useful in tests that are meant to be deterministic, such as snapshot tests.
import { faker } from '@faker-js/faker/locale/en';
import { afterEach, describe, expect, it } from 'vitest';
// We might want other tests to *not* be seeded. This will re-seed our faker instance after each test.
afterEach(() => {
faker.seed();
});
describe('reverse array', () => {
it('should reverse the array', () => {
// Seed our faker instance with some static number.
faker.seed(1234);
const title = faker.person.jobTitle();
const name = faker.person.fullName();
const animal = faker.animal.bear();
const array = [title, name, animal];
expect(array.reverse()).toStrictEqual([animal, name, title]);
// Expect our value to always match a generated snapshot.
expect(array.reverse()).toMatchSnapshot();
});
});Cypress
Cypress integration is fairly straightforward as well:
import { faker } from '@faker-js/faker/locale/en';
describe('Testing the application', () => {
it('should create an account with username and password', () => {
let username = faker.internet.username();
let password = faker.internet.password();
let email = faker.internet.exampleEmail();
// Visit the a webpage and create an account.
cy.visit('https://www.example.com/register');
cy.get('#email-input').type(email);
cy.get('#username-input').type(username);
cy.get('#password-input').type(password);
cy.get('#password-confirm-input').type(password);
cy.get('#register-submit-input').click();
// Now, we try to login with these credentials.
cy.visit('https://www.example.com/login');
cy.get('#email-input').type(email);
cy.get('#password-input').type(password);
cy.get('#login-submit-input').click();
// We should have logged in successfully to the dashboard page.
cy.url().should('include', '/dashboard');
});
});Playwright
Integration with Playwright is also easy:
import { faker } from '@faker-js/faker/locale/en';
import { expect, test } from '@playwright/test';
test.describe('Testing the application', () => {
test('should create an account with username and password', async ({
page,
}) => {
const username = faker.internet.username();
const password = faker.internet.password();
const email = faker.internet.exampleEmail();
// Visit the webpage and create an account.
await page.goto('https://www.example.com/register');
await page.getByLabel('email').fill(email);
await page.getByLabel('username').fill(username);
await page.getByLabel('password', { exact: true }).fill(password);
await page.getByLabel('confirm password').fill(password);
await page.getByRole('button', { name: 'Register' }).click();
// Now, we try to login with these credentials.
await page.goto('https://www.example.com/login');
await page.getByLabel('email').fill(email);
await page.getByLabel('password').fill(password);
await page.getByRole('button', { name: 'Login' }).click();
// We should have logged in successfully to the dashboard page.
await expect(page).toHaveURL(/.*dashboard/);
});
});File: docs/guide/index.md
Getting Started
Overview
Faker is a popular library that generates fake (but reasonable) data that can be used for things such as:
- Unit Testing
- Performance Testing
- Building Demos
- Working without a completed backend
Faker was originally written in Perl and this is the JavaScript port. Faker is also available as a library for Ruby, Java, and Python.
This documentation only covers the JavaScript implementation of Faker.
Environments
You can run Faker in the browser, or in Node.js. Faker v11.0 requires Node.js version 22 or above.
Installation
Install it as a Dev Dependency using your favorite package manager.
::: code-group
npm install @faker-js/faker --save-devpnpm add @faker-js/faker --save-devyarn add @faker-js/faker --devdeno add --dev @faker-js/faker:::
Faker Modules
Faker has three types of modules:
- Modules for basic datatypes:
datatype,date,numberandstring - Topic specific modules, such as
animal,foodand many more - Lastly, the
helpersmodule, with various utility methods to use with your own data (or data generated by other Faker methods)
For a full list of modules, go to our Api Search page.
If you would like to know how to use Faker, go to our Usage Guide page.
Community
If you have questions or need help, reach out to the community via Discord and GitHub Discussions.
You can see awesome things related to the Faker community at Awesome Faker.
File: docs/guide/localization.md
Localization
Switching locales
Did you know Faker supports many different locales?
When using our default instance import { faker } from '@faker-js/faker' you get English data.
However, we also provide pre-built instances for more than 70 available locales.
For example, you can import the German locale:
import { fakerDE as faker } from '@faker-js/faker'
::: tip Note
You can also build your own Faker instances, with custom locales/overwrites.
:::
Custom locales and fallbacks
If our built-in faker instances don't satisfy your needs, you can build your own:
import type { LocaleDefinition } from '@faker-js/faker';
import { base, de, de_CH, en, Faker } from '@faker-js/faker';
const customLocale: LocaleDefinition = {
title: 'My custom locale',
internet: {
domainSuffix: ['test'],
},
};
export const customFaker = new Faker({
locale: [customLocale, de_CH, de, en, base],
});In this example there are 5 locales. Each of these is checked in order, and the first locale which contains the requested data will be used:
customLocaleis your custom locale definition which will override all other fallback definitions.de_CHis a specific locale definition that overrides some German definitions withCH(Switzerland) data.deis a genericde(German) locale definition.enis a genericen(English) locale definition. This is our most complete locale, so we add it to fill some gaps. Depending on your needs, you might want or not want to have it as a fallback.baseis the base locale definition which contains definitions that can be used in every language (e.g. emojis).
Available locales
| Locale | Name | Faker |
|---|---|---|
af_ZA |
Afrikaans (South Africa) | fakerAF_ZA |
ar |
Arabic | fakerAR |
az |
Azerbaijani | fakerAZ |
base |
Base | fakerBASE |
bn_BD |
Bengali (Bangladesh) | fakerBN_BD |
cs_CZ |
Czech (Czechia) | fakerCS_CZ |
cy |
Welsh | fakerCY |
da |
Danish | fakerDA |
de |
German | fakerDE |
de_AT |
German (Austria) | fakerDE_AT |
de_CH |
German (Switzerland) | fakerDE_CH |
dv |
Maldivian | fakerDV |
el |
Greek | fakerEL |
en |
English | fakerEN |
en_AU |
English (Australia) | fakerEN_AU |
en_AU_ocker |
English (Australia Ocker) | fakerEN_AU_ocker |
en_BORK |
English (Bork) | fakerEN_BORK |
en_CA |
English (Canada) | fakerEN_CA |
en_GB |
English (Great Britain) | fakerEN_GB |
en_GH |
English (Ghana) | fakerEN_GH |
en_HK |
English (Hong Kong) | fakerEN_HK |
en_IE |
English (Ireland) | fakerEN_IE |
en_IN |
English (India) | fakerEN_IN |
en_NG |
English (Nigeria) | fakerEN_NG |
en_NP |
English (Nepal) | fakerEN_NP |
en_US |
English (United States) | fakerEN_US |
en_ZA |
English (South Africa) | fakerEN_ZA |
eo |
Esperanto | fakerEO |
es |
Spanish | fakerES |
es_MX |
Spanish (Mexico) | fakerES_MX |
fa |
Farsi/Persian | fakerFA |
fi |
Finnish | fakerFI |
fr |
French | fakerFR |
fr_BE |
French (Belgium) | fakerFR_BE |
fr_CA |
French (Canada) | fakerFR_CA |
fr_CH |
French (Switzerland) | fakerFR_CH |
fr_LU |
French (Luxembourg) | fakerFR_LU |
fr_SN |
French (Senegal) | fakerFR_SN |
he |
Hebrew | fakerHE |
hr |
Croatian | fakerHR |
hu |
Hungarian | fakerHU |
hy |
Armenian | fakerHY |
id_ID |
Indonesian (Indonesia) | fakerID_ID |
it |
Italian | fakerIT |
ja |
Japanese | fakerJA |
ka_GE |
Georgian (Georgia) | fakerKA_GE |
ko |
Korean | fakerKO |
ku_ckb |
Kurdish (Sorani) | fakerKU_ckb |
ku_kmr_latin |
Kurdish (Kurmanji, Latin) | fakerKU_kmr_latin |
lv |
Latvian | fakerLV |
mk |
Macedonian | fakerMK |
mn_MN_cyrl |
Mongolian (Mongolia, Cyrillic) | fakerMN_MN_cyrl |
nb_NO |
Norwegian (Norway) | fakerNB_NO |
ne |
Nepali | fakerNE |
nl |
Dutch | fakerNL |
nl_BE |
Dutch (Belgium) | fakerNL_BE |
pl |
Polish | fakerPL |
pt_BR |
Portuguese (Brazil) | fakerPT_BR |
pt_PT |
Portuguese (Portugal) | fakerPT_PT |
ro |
Romanian | fakerRO |
ro_MD |
Romanian (Moldova) | fakerRO_MD |
ru |
Russian | fakerRU |
sk |
Slovak | fakerSK |
sl_SI |
Slovenian (Slovenia) | fakerSL_SI |
sr_RS_latin |
Serbian (Serbia, Latin) | fakerSR_RS_latin |
sv |
Swedish | fakerSV |
ta_IN |
Tamil (India) | fakerTA_IN |
th |
Thai | fakerTH |
tr |
Turkish | fakerTR |
uk |
Ukrainian | fakerUK |
ur |
Urdu | fakerUR |
uz_UZ_latin |
Uzbek (Uzbekistan, Latin) | fakerUZ_UZ_latin |
vi |
Vietnamese | fakerVI |
yo_NG |
Yoruba (Nigeria) | fakerYO_NG |
zh_CN |
Chinese (China) | fakerZH_CN |
zh_TW |
Chinese (Taiwan) | fakerZH_TW |
zu_ZA |
Zulu (South Africa) | fakerZU_ZA |
The Locale (data) and Faker columns refer to the respective import names:
import { de, fakerDE } from '@faker-js/faker';::: tip Note
Some locales have limited coverage and rely more heavily on the English locale as the source for features they currently do not have.
However, in most cases, using a specific locale will be beneficial in the long term as specifying a locale reduces the time necessary for startup, which has a compounding effect on testing frameworks that reload the imports every execution.
:::
Locale codes
Locales are named in a systematic way. The first two characters are a lowercase language code following the ISO 639-1 standard for example ar for Arabic or en for English.
The same language may be spoken in different countries, with different patterns for addresses, phone numbers etc. Optionally a two-letter uppercase country code can be added after an underscore, following the ISO 3166-1 alpha-2 standard, for example en_US represents English (United States) and en_AU represents English (Australia).
Rarely, an additional variant may be needed to fully represent an accented variant of the locale, or for languages which can be written in different scripts. This is appended after another underscore, for example en_AU_ocker (English in Australia in "Ocker" dialect) or sr_RS_latin (Serbian in Serbia in Latin script).
The recommended way to access Faker instances is by using one of the individual imports as shown above. If needed you can access all prebuilt Faker instances or all locale definitions via an object where the locale codes are the keys:
import { allFakers, allLocales } from '@faker-js/faker';
console.dir(allFakers['de_AT']); // the prebuilt Faker instance for de_AT
console.dir(allLocales['de_AT']); // the raw locale definitions for de_ATThis could be useful if you want to enumerate all locales, for example:
import { allFakers } from '@faker-js/faker';
for (let key of Object.keys(allFakers)) {
try {
console.log(
`In locale ${key}, a sample name is ${allFakers[key].person.fullName()}`
);
} catch (e) {
console.log(`In locale ${key}, an error occurred: ${e}`);
}
}Handling Missing Data Errors
[Error]: The locale data for 'category.entry' are missing in this locale.
Please contribute the missing data to the project or use a locale/Faker instance that has these data.
For more information see https://fakerjs.dev/guide/localization.htmlIf you receive this error, this means you are using a locale (Faker instance) that does not have the relevant data for that method yet.
Please consider contributing the missing data, so that others can use them in the future as well.
As a workaround, you can provide additional fallbacks to your Faker instance:
import { Faker, el } from '@faker-js/faker'; // [!code --]
import { Faker, base, el, en } from '@faker-js/faker'; // [!code ++]
const faker = new Faker({
locale: [el], // [!code --]
locale: [el, en, base], // [!code ++]
});
console.log(faker.location.country()); // 'Belgium'::: tip Note
Of course, you can use Custom Locales and Fallbacks for this as well.
:::
Handling Not-Applicable Data Errors
[Error]: The locale data for 'category.entry' aren't applicable to this locale.
If you think this is a bug, please report it at: https://github.com/faker-js/fakerIf you receive this error, this means the current locale is unable to provide reasonable values for that method.
For example, there are no zip codes in Hongkong, so for that reason the en_HK locale is unable to provide these data.
The same applies to other locales and methods.
import { fakerEN_HK } from '@faker-js/faker';
console.log(fakerEN_HK.location.zipCode()); // Error // [!code error]For these cases, we explicitly set the data to null to clarify, that we have thought about it, but there are no valid values to put there.
We could have used an empty array [], but some locale data are stored as objects {},
so null works for both of them without custom downstream handling of missing data.
::: tip Note
We are by far no experts in all provided languages/countries/locales,
so if you think this is an error for your locale, please create an issue and consider contributing the relevant data.
:::
If you want to use other fallback data instead, you can define them like this:
import { Faker, en, en_HK } from '@faker-js/faker';
const faker = new Faker({
locale: [{ location: { postcode: en.location.postcode } }, en_HK],
});
console.log(faker.location.zipCode()); // '17551-0348'::: warning Warning
Since null is considered present data, it will not use any fallbacks for that.
So the following code does not work:
import { Faker, en, en_HK } from '@faker-js/faker';
const faker = new Faker({
locale: [en_HK, { location: { postcode: en.location.postcode } }], // [!code warning]
});
console.log(faker.location.zipCode()); // Error // [!code error]:::
See also: Custom Locales and Fallbacks
File: docs/guide/randomizer.md
Randomizer
The Randomizer interface allows you to use a custom randomness source within Faker.
::: warning Important
Faker's default Randomizer is sufficient in most cases.
Change this only if you want to use it to achieve a specific goal, such as sharing the same random generator with other instances/tools.
:::
There are two connected use cases we have considered where this might be needed:
- Re-Use of the same
Randomizerwithin multipleFakerinstances. - The use of a random number generator from a third party library.
Built-In `Randomizer`s
Faker ships with two variations
import {
generateMersenne32Randomizer, // Default prior to v9
generateMersenne53Randomizer, // Default since v9
} from '@faker-js/faker';
const randomizer = generateMersenne53Randomizer();The 32bit Randomizer is faster, but the 53bit Randomizer generates better random values (with significantly fewer duplicates).
But you can also implement your own by implementing the related interface.
Using `Randomizer`s
A Randomizer has to be set during construction of the instance:
import { Faker, Randomizer } from '@faker-js/faker';
const customFaker = new Faker({
locale: ...,
randomizer: ...,
});The following methods take a Randomizer as argument:
Re-Using a `Randomizer`
Sometimes it might be required to generate values in two different locales.
E.g. a Chinese person might have an English identity to simplify the communication with foreigners.
While this could also be achieved with two independent Faker instances like this:
import { fakerEN, fakerZH_TW } from '@faker-js/faker';
fakerZH_TW.seed(5);
fakerEN.seed(5);
const firstName = fakerZH_TW.person.firstName(); // ็ซๆ
const alias = fakerEN.person.firstName(); // ArthurThere might be issues regarding reproducibility, when seeding only one of them.
By sharing a Randomizer between the two instances, you omit this issue by affecting all instances simultaneously.
::: tip Note
This gets more important if the seeding happens at a different location than the data generation (e.g. due to nesting).
:::
import { en, Faker, Randomizer, zh_TW } from '@faker-js/faker';
const randomizer: Randomizer = ...;
const customFakerEN = new Faker({
locale: en,
randomizer,
});
const customFakerZH_TW = new Faker({
locale: [zh_TW, en],
randomizer,
});
randomizer.seed(5);
// customFakerEN.seed(5); // Redundant
// customFakerZH_TW.seed(5); // Redundant
const firstName = fakerZH_TW.person.firstName(); // ็ซๆ
const alias = fakerEN.person.firstName(); // John (different from before, because it is now the second call)This is also relevant when trying to use faker's random number generator in third party libraries.
E.g. some libraries that can generate strings from a RegExp can be customized with a custom random number generator as well,
and since they will be used in the same context it makes sense to rely on the same randomness source to ensure the values are reproducible.
Third-Party `Randomizer`s
Sometimes you might want to use a custom/third-party random number generator.
This can be achieved by implementing your own Randomizer and passing it to supported methods.
::: tip Note
Faker does not ship Randomizers for third-party libraries and does not provide support for bridging the gap between libraries.
The following examples show how the interface can be implemented, but they are not tested for correctness.
Feel free to submit more Randomizer examples for other popular packages.
:::
Pure-Rand
The following is an example for a pure-rand based Randomizer:
import { Faker, Randomizer, SimpleFaker } from '@faker-js/faker';
import { RandomGenerator, xoroshiro128plus } from 'pure-rand';
export function generatePureRandRandomizer(
seed: number | number[] = Date.now() ^ (Math.random() * 0x100000000),
factory: (seed: number) => RandomGenerator = xoroshiro128plus
): Randomizer {
const self = {
next: () => (self.generator.unsafeNext() >>> 0) / 0x100000000,
seed: (seed: number | number[]) => {
self.generator = factory(typeof seed === 'number' ? seed : seed[0]);
},
} as Randomizer & { generator: RandomGenerator };
self.seed(seed);
return self;
}File: docs/guide/unique.md
Unique Values
In general, Faker methods do not return unique values.
faker.seed(55);
faker.animal.type(); //'cat'
faker.animal.type(); //'bird'
faker.animal.type(); //'horse'
faker.animal.type(); //'horse'Some methods and locales use much smaller data sets than others. For example, faker.animal.type has only 44 possible animals to choose from. In contrast, faker.person.fullName() pulls from a list of hundreds of first names, surnames, and prefixes/suffixes, so it can generate hundreds of thousands of unique names. Even then, the birthday paradox means that duplicate values will quickly be generated.
Sometimes, you want to generate unique values. For example, you may wish to have unique values in a database email column.
There are a few possible strategies for this:
- Use
faker.helpers.uniqueArray()if you want to generate all the values at one time. For example:
faker.helpers.uniqueArray(faker.internet.email, 1000); // will generate 1000 unique email addressesIf there are insufficient values for your needs, consider prefixing or suffixing values with your own sequential values, for example you could prefix
1.,2.to each generated email in turn.Build your own logic to keep track of a set of previously generated values and regenerate values as necessary if a duplicate is generated
Use a third-party package to enforce uniqueness, such as enforce-unique or @dpaskhin/unique.
File: docs/guide/upgrading.md
outline: [2, 3]
Upgrading to v10
This is the migration guide for upgrading from v9 to v10.
::: info Not the version you are looking for?
:::
General Breaking Changes
Node v18 No Longer Supported
Support for Node.js v18 has been discontinued, as this version has reached its end-of-life. Faker.js v10 requires a minimum of Node.js v20.19.0, v22.13.0, or v24.0.0.
CommonJS Still Supported, but Check Your Versions
Node
Technically, Faker v10 is now an ESM-only package. However, the good news is that you can still use it from your CommonJS projects without code changes, thanks to the ESM Modules require feature in recent versions of Node.js.
If you are using Node 20 or Node 22, ensure you are using a sufficiently recent minor versionโNode v20.19+ or Node v22.13+ is required.
const { faker, fakerES } = require('@faker-js/faker'); // this still worksIf your version of Node.js is too old, you may see an error like:
Uncaught:
Error [ERR_REQUIRE_ESM]: require() of ES Module /faker/dist/index.js not supported.
Instead, change the require of index.js in null to a dynamic import(), which is available in all CommonJS modules.TypeScript
As mentioned in the previous section, CJS can still be used if you use a modern module resolution strategy. This directly impacts your tsconfig.json setup.
Previously, you were able to provide the values "Bundler", "Node10", "Node16" or "NodeNext" for the configuration "moduleResulution". Starting in v10 of Faker, only the values "Bundler", "Node20" or "NodeNext" are supported for your CJS codebase. To use "Node20" your typescript version must be at least 5.9.0.
Jest
Because Jest testing library uses its own module resolution system, there are known compatibility issues with Faker v10 in combination with CJS in the Jest tests.
If any below solutions fails, keep using Faker v9. You can find some more details and possible workarounds in issue #3606.
Jest `>=30.4.2` with native ESM support
Starting with Jest v30.4.2, the transformIgnorePatterns workaround below is no longer needed. Instead, enable Jest's native ESM support by setting the NODE_OPTIONS environment variable when running your tests:
NODE_OPTIONS="--experimental-vm-modules" npx jestNote that for require-based (CJS) test files this additionally requires Node.js v24.9.0 or newer, as Jest relies on its synchronous vm module APIs to require ESM packages. On older Node.js versions, Jest fails with an error explaining exactly that.
`ts-jest`
When using Jest in a TypeScript project you might be already using ts-jest for transforming ts files on the fly. In such case you should apply following changes to your jest.config.ts:
// Transform both `ts` and `js` files. Defining only `ts` would not be enough, as we also need to transform @faker-js
transform: {
'^.+\\.(t|j)s$': 'ts-jest',
// or when you pass more settings:
'^.+\\.(t|j)s$': [
'ts-jest',
// ... other setttings
]
}
// Exclude from transformation all files in `node_modules`, except `@faker-js`
transformIgnorePatterns: [
// npm
'node_modules/(?!@faker-js).+',
// pnpm
'node_modules/.pnpm/.+/node_modules/(?!@faker-js).+'
],Check more in our playground.
Removal of Deprecated Code
A number of methods that were deprecated in v9 have been completely removed in v10. To prepare for the upgrade, it is recommended to first upgrade to the latest version of v9 (e.g., npm install --save-dev faker@9) and fix any deprecation warnings issued by your code.
| Removed Method | Replacement |
|---|---|
faker.address.* |
faker.location.* |
faker.name.* |
faker.person.* |
faker.internet.userName |
faker.internet.username |
Some methods do not have exact replacements, so check your code carefully.
| Removed Method | Replacement / Notes |
|---|---|
faker.internet.color |
faker.color.rgb |
faker.image.urlPlaceholder |
faker.image.dataUri |
faker.finance.maskedNumber |
See #3201 |
faker.image.avatarLegacy |
faker.image.avatar |
Word Methods Default Resolution Strategy
The default resolution strategy for the methods in the word module changed to 'fail'.
This means that methods in the word module will throw an error if no words for your input criteria exist.
// There are no nouns between 20-25 characters long in the word list
faker.word.noun({ length: { min: 20, max: 25 } });
// In v9, this would return a random noun of any length, like 'plastic'
// In v10, this throws an error `FakerError: No words found that match the given length.`Previously, the methods would return a random word, completely ignoring the the length requirements you specified.
If you want to restore this behavior, you can provide the 'any-length' strategy to the word methods.
| Method in v9 | Method in v10 with v9 behavior |
|---|---|
faker.word.adjective() |
faker.word.adjective({ strategy: 'any-length' }) |
faker.word.adverb() |
faker.word.adverb({ strategy: 'any-length' }) |
faker.word.conjunction() |
faker.word.conjunction({ strategy: 'any-length' }) |
faker.word.interjection() |
faker.word.interjection({ strategy: 'any-length' }) |
faker.word.noun() |
faker.word.noun({ strategy: 'any-length' }) |
faker.word.preposition() |
faker.word.preposition({ strategy: 'any-length' }) |
faker.word.sample() |
faker.word.sample({ strategy: 'any-length' }) |
faker.word.verb() |
faker.word.verb({ strategy: 'any-length' }) |
File: docs/guide/usage.md
Usage
Node.js
Using Faker is as easy as importing it from @faker-js/faker.
::: code-group
import { faker } from '@faker-js/faker';
// or, if desiring a different locale
// import { fakerDE as faker } from '@faker-js/faker';
const randomName = faker.person.fullName(); // Rowan Nikolaus
const randomEmail = faker.internet.email(); // [email protected]const { faker } = require('@faker-js/faker');
// or, if desiring a different locale
// const { fakerDE: faker } = require('@faker-js/faker');
const randomName = faker.person.fullName(); // Rowan Nikolaus
const randomEmail = faker.internet.email(); // [email protected]:::
For more information on selecting and customizing a locale, please refer to our Localization Guide.
Browser
If you want to try it yourself, you can open your browser console via Ctrl + Shift + J / F12.
On our website, you can load faker into the browser console
- by using
await enableFaker() - or using the following code:
const { faker } = await import('https://esm.sh/@faker-js/faker');
const randomName = faker.person.fullName(); // Amber Keebler
const randomEmail = faker.internet.email(); // [email protected]Some websites may have protections against downloading external code, dev servers usually work fine.
As an alternative, you can create a simple html file and open it with your browser:
<script type="module">
import { faker } from 'https://esm.sh/@faker-js/faker';
// Caitlyn Kerluke
const randomName = faker.person.fullName();
// [email protected]
const randomEmail = faker.internet.email();
document.getElementById('name').value = randomName;
document.getElementById('email').value = randomEmail;
</script>::: info Note
Using the browser is great for experimenting ๐. However, due to all of the strings Faker uses to generate fake data, Faker is a large package. It's > 5 MiB minified. Please avoid deploying the full Faker package in your web app.
:::
CDN/Deno
import { faker } from 'https://esm.sh/@faker-js/faker';
const randomName = faker.person.fullName(); // Willie Bahringer
const randomEmail = faker.internet.email(); // [email protected]::: info Note
It is highly recommended to use version tags when importing libraries in Deno, e.g: import { faker } from "https://esm.sh/@faker-js/[email protected]".
:::
Alternative CDN links
esm:
cjs:
TypeScript Support
We assume that you use TypeScript (strict mode).
You can use Faker without it, but we don't have dedicated error messages for wrong parameter types.
In order to have Faker working properly, you need to check if these compilerOptions are set correctly in your tsconfig file:
::: code-group
{
"compilerOptions": {
"moduleResolution": "Bundler", // or "Node10", "Node16", "Node20", "NodeNext"
"strict": true // Optional, but recommended
}
}{
"compilerOptions": {
"moduleResolution": "Bundler", // or "Node20" or "NodeNext"
"strict": true // Optional, but recommended
}
}:::
Reproducible results
Normally Faker will give you different random values each time it is used.
faker.music.genre(); // "Soul"
faker.music.genre(); // "Reggae"If you want consistent results, you can set your own seed:
faker.seed(123);
const firstRandom = faker.number.int();
// Setting the seed again resets the sequence.
faker.seed(123);
const secondRandom = faker.number.int();
console.log(firstRandom === secondRandom);::: info Note
When upgrading to a new version of Faker, you may get different values for the same seed, as the underlying data (lists of names, words etc) may have changed.
:::
There are a few methods which use relative dates for which setting a random seed is not sufficient to have reproducible results, for example: faker.date.past, faker.date.future, faker.date.recent, faker.date.soon, faker.git.commitEntry and faker.string.uuid({ version: 7 }). This is because these methods default to creating a date before or after "today", and "today" depends on when the code is run. To fix this, you can specify a fixed reference date as a Date or string, for example:
// creates a date soon after 2023-01-01
faker.date.soon({ refDate: '2023-01-01T00:00:00.000Z' });or alternatively you can set a default reference date for all these methods:
// affects all future faker.date.* calls
faker.setDefaultRefDate('2023-01-01T00:00:00.000Z');Simple data generation
Faker provides a simpleFaker that can be used to generate data that are not based on any locales like numbers and strings.
Also helpers like arrayElement or multiple are available.
This is useful if you just want to generate e.g. uuids for your test environment, but don't want/need to initiate/load a full Faker instance, which would include at least 500KB of locale data.
import { simpleFaker } from '@faker-js/faker';
const uuid = simpleFaker.string.uuid();See more about SimpleFaker in the API docs.
Create complex objects
Faker mostly generates values for primitives.
This is because in the real world, most object schemas simply look very different.
So, if you want to create an object, you most likely need to write a factory function for it.
For our example, we use TypeScript to strongly type our model.
The models we will use are described below:
import type { SexType } from '@faker-js/faker';
type SubscriptionTier = 'free' | 'basic' | 'business';
interface User {
_id: string;
avatar: string;
birthday: Date;
email: string;
firstName: string;
lastName: string;
sex: SexType;
subscriptionTier: SubscriptionTier;
}As you can see, our User model probably looks completely different from the one you have in your codebase.
One thing to keep an eye on is the subscriptionTier property, as it is not simply a string, but only one of the strings defined in the SubscriptionTier type ('free' or 'basic' or 'business').
Also, in a real scenario, your model should not depend on a type of a third party library (SexType in this case).
Let's create our first user factory function:
import { faker } from '@faker-js/faker';
interface User { ... }
function createRandomUser(): User {
return {
_id: faker.string.uuid(),
avatar: faker.image.avatar(),
birthday: faker.date.birthdate(),
email: faker.internet.email(),
firstName: faker.person.firstName(),
lastName: faker.person.lastName(),
sex: faker.person.sexType(),
subscriptionTier: faker.helpers.arrayElement(['free', 'basic', 'business']),
};
}
const user = createRandomUser();At this point, we have a perfectly working function that will work for most purposes.
But we can take this a step further.
Currently, all properties are just randomly generated.
This can lead to some undesirable values being produced.
For example: The sex property having value 'female' while firstName is 'Bob'.
Let's refactor our current code:
import { faker } from '@faker-js/faker';
function createRandomUser(): User {
const sex = faker.person.sexType();
const firstName = faker.person.firstName(sex);
const lastName = faker.person.lastName();
const email = faker.internet.email({ firstName, lastName });
return {
_id: faker.string.uuid(),
avatar: faker.image.avatar(),
birthday: faker.date.birthdate(),
email,
firstName,
lastName,
sex,
subscriptionTier: faker.helpers.arrayElement(['free', 'basic', 'business']),
};
}
const user = createRandomUser();As you can see, we changed the order in which we generate our values.
First, we generate a sex value to use it as input for the generation of firstName.
Then we generate the lastName.
Here, we could also pass in the sex value as argument, but in our use-case there are no special cases in where a female last name would differ from a male one.
By doing this first, we are able to pass both names into the email generation function.
This allows the value to be more reasonable based on the provided arguments.
Unlike the _id property that uses an uuid implementation, which has a low chance of duplicates, the email function is more likely to produce duplicates, especially if the call arguments are similar. We have a dedicated guide page on generating unique values.
The example above demonstrates how to generate complex objects.
To gain more control over the values of specific properties, you can introduce overwrites, options or similar parameters:
import { faker } from '@faker-js/faker';
function createRandomUser(overwrites: Partial = {}): User {
const {
_id = faker.string.uuid(),
avatar = faker.image.avatar(),
birthday = faker.date.birthdate(),
sex = faker.person.sexType(),
firstName = faker.person.firstName(sex),
lastName = faker.person.lastName(),
email = faker.internet.email({ firstName, lastName }),
subscriptionTier = faker.helpers.arrayElement([
'free',
'basic',
'business',
]),
} = overwrites;
return {
_id,
avatar,
birthday,
email,
firstName,
lastName,
sex,
subscriptionTier,
};
}
const user = createRandomUser();
const userToReject = createRandomUser({ birthday: new Date('2124-10-20') });A potential options parameter could be used to:
- control which optional properties are included,
- control how nested elements and arrays are merged or replaced,
- or specify the number of items to generate for nested lists.
Congratulations, you should now be able to create any complex object you desire.
Happy faking ๐ฅณ.
File: docs/contributing/code-of-conduct.md
editLink: false
Code of Conduct
We welcome new contributors!
We appreciate your interest in making Faker a better library.
Please note that all contributors are expected to follow the Code of Conduct.
File: docs/contributing/propose-a-feature.md
Propose a Feature
If you want to propose a new feature in Faker, please create a new issue using the Feature Request Template.
@faker-js/faker is all about enhancing the developer experience with realistic fake data.
As our library grows, we welcome contributions that introduce new features and maintain the cohesive functionality of our existing codebase.
To ensure quality and consistency, we have established guidelines for contributing new features.
General Feature Guidelines
General criteria for new features are as follows:
- Relevance: Must be widely applicable and not specific to a particular niche.
- Deterministic: Functions must be based on Faker's internal Randomizer.
- Conflict-Free: Should not conflict with or duplicate existing features.
- Utility: Provides significant value to a broad user base.
- Library-Agnostic: Implementations must be based solely on JavaScript runtime environments and not on specific libraries or frameworks.
Accepting a Feature
In order for a feature to be accepted in Faker, it must fulfill all the criteria listed in General Feature Guideline.
Additionally, depending on the type of feature, there might be additional requirements.
::: tip Note
Using thumb-up emojis ( :+1: ) on issues helps the Faker estimate the community interest in a feature.
If you see a feature request that you like, leave an up vote to increase interest.
Feel free to upvote your own feature requests as well.
:::
Criteria for New Locales
Faker already contains over 70 different locales.
If you want to propose a new locale that does not already exist, make sure to read our guide on locale code names.
You should be able to name your locale using the provided naming standards.
Ideally, you should also use this name in the issue's title and description.
Considerations
Our goal is to maintain the library efficiently, ensuring that new features are indispensable.
Each addition to Faker comes with associated costs.
This encompasses initial expenses like design, implementation, review, and documentation of the feature.
Ideally, these tasks can be delegated to the requester or another member of the community.
Moreover, ongoing maintenance of Faker incurs further costs, including awareness of the feature, a more intricate module structure, increased bundle size, and additional effort during refactoring.
If your feature isn't accepted into the library, you can still create it using Faker's Helper methods.
Our goal is to empower developers, not limit possibilities.
For more details on creating custom features, refer to our documentation on Create Complex Objects.