Tutorial - Configuring TypeScript, Express, Jest, Payload, and VSCode Debugging from Scratch

Published On
Tutorial - Configuring TypeScript, Express, Jest, Payload, and VSCode Debugging from Scratch
Tutorial - Configuring TypeScript, Express, Jest, Payload, and VSCode Debugging from Scratch

Setting up a TypeScript project from scratch can be intimidating. Bring in Jest, VSCode debugging, and a headless CMS - and there are many moving parts. But it doesn't have to be difficult!

We've been working hard at making Payload + TypeScript a match made in heaven, and over the last few months we've released a suite of features, including automatic type generation, which makes Payload by far the best TypeScript headless CMS available. To celebrate, we're going to show you how to scaffold a TypeScript and Express project from scratch, including testing it with Jest and debugging with VSCode.

By understanding just a few new concepts, you can master your dev environment's setup to maximize productivity and gain a deep understanding how it all works together. Let's get started.

Software Requirements

Before going further, make sure you have the following software:

  • Yarn or NPM
  • NodeJS
  • A Mongo Database

Step 1 - initialize a new project

Create a new folder, cd into it, and initialize:

1
mkdir ts-payload && cd ts-payload && yarn init

Step 2 - install dependencies

We'll need a few baseline dependencies:

  • dotenv - to set up our environment easily
  • express - Payload is built on top of Express
  • ts-node - to execute our TypeScript project in development mode
  • typescript - base TS dependency
  • payload - no description necessary
  • nodemon - to make sure our project restarts automatically when files change

Install these dependencies by running:

1
yarn add dotenv express payload

and the rest as devDependencies using:

1
yarn add --dev nodemon ts-node typescript

Step 3 - create a tsconfig:

In the root of your project folder, create a new file called tsconfig.json and add the following content to it. This file tells the TS compiler how to behave, including where to write its output files.

Example tsconfig.json:

1
{
2
"compilerOptions": {
3
"target": "es5",
4
"lib": [
5
"dom",
6
"dom.iterable",
7
"esnext"
8
],
9
"outDir": "./dist",
10
"skipLibCheck": true,
11
"strict": false,
12
"esModuleInterop": true,
13
"module": "commonjs",
14
"moduleResolution": "node",
15
"allowSyntheticDefaultImports": true,
16
"resolveJsonModule": true,
17
"isolatedModules": true,
18
"jsx": "preserve",
19
"sourceMap": true
20
},
21
"include": [
22
"src"
23
],
24
"ts-node": {
25
"transpileOnly": true
26
}
27
}

In the above example config, we're planning to keep all of our TypeScript files in /src, and then build to /dist.

Step 4 - set up your .env file

We'll be using dotenv to manage our environment and get ourselves set up for deployment to various different environments like staging and production later down the road. The dotenv package will read all values in a .env file within our project root and bind their values to process.env so that you can access them in your code.

Let's create a .env file in the root folder of your project and add the following:

1
PORT=3000
2
MONGO_URL=mongodb://localhost/your-project-name
3
PAYLOAD_SECRET_KEY=alwifhjoq284jgo5w34jgo43f3
4
PAYLOAD_CONFIG_PATH=src/payload.config.ts
5
PAYLOAD_PUBLIC_SERVER_URL=http://localhost:3000

Make sure that the MONGO_URL line in your .env matches an available MongoDB instance. If you have Mongo running locally on your computer, the line above should work right out of the box, but if you want to use a hosted MongoDB like Mongo Atlas, make sure you copy and paste the connection string from your database and update your .env accordingly.

For more information on what these values do, take a look at Payload's Getting Started docs.

Step 5 - create your server

Setting up an Express server might be pretty familiar. Create a src/server.ts file in your project and add the following to the file:

1
import express from 'express';
2
import payload from 'payload';
3
import path from 'path';
4
5
// Use `dotenv` to import your `.env` file automatically
6
require('dotenv').config({
7
path: path.resolve(__dirname, '../.env'),
8
});
9
10
const app = express();
11
12
payload.init({
13
secret: process.env.PAYLOAD_SECRET_KEY,
14
mongoURL: process.env.MONGO_URL,
15
express: app,
16
})
17
18
app.listen(process.env.PORT, async () => {
19
console.log(`Express is now listening for incoming connections on port ${process.env.PORT}.`)
20
});

The file above first imports our server dependencies. Then, we use dotenv to load our .env file at our project root. Next, we initialize Payload by providing it with our secret key, Mongo connection string, and Express app. Finally, we tell our Express app to listen on the port defined in our .env file.

Step 6 - create a nodemon file

We'll use Nodemon to automatically restart our server when any .ts files change within our ./src directory. Nodemon will execute ts-node for us, which will use our server as its entry point. Create a nodemon.json file within the root of your project and add the following content.

Example nodemon.json:

1
{
2
"watch": [
3
"./src/**/*.ts"
4
],
5
"exec": "ts-node ./src/server.ts"
6
}

Step 7 - add your Payload config

The Payload config is central to everything Payload does. Add it to your src folder and enter the following baseline code:

./src/payload.config.ts:

1
import dotenv from 'dotenv';
2
import path from 'path';
3
import { buildConfig } from 'payload/config';
4
5
dotenv.config({
6
path: path.resolve(__dirname, '../.env'),
7
});
8
9
export default buildConfig({
10
serverURL: process.env.PAYLOAD_PUBLIC_SERVER_URL,
11
typescript: {
12
outputFile: path.resolve(__dirname, './generated-types.ts'),
13
},
14
collections: [
15
{
16
slug: 'posts',
17
admin: {
18
useAsTitle: 'title',
19
},
20
fields: [
21
{
22
name: 'title',
23
type: 'text',
24
},
25
{
26
name: 'author',
27
type: 'relationship',
28
relationTo: 'users',
29
},
30
]
31
}
32
]
33
});

This config is very basic - but check out the Config docs for more on what the Payload config can do. Out of the box, this config will give you a default Users collection, a simple Posts collection with a few fields, and will open up the admin panel to you at http://localhost:3000/admin.

The config also specifies where Payload should output its auto-generated TypeScript types which is super cool (we'll come back to this).

Step 8 - add some NPM scripts

The last step before we can fire up our project is to add some development, build, and production NPM scripts.

Open your package.json and update the scripts property to the following:

1
{
2
"scripts": {
3
"generate:types": "PAYLOAD_CONFIG_PATH=src/payload.config.ts payload generate:types",
4
"dev": "nodemon",
5
"build:payload": "PAYLOAD_CONFIG_PATH=src/payload.config.ts payload build",
6
"build:server": "tsc",
7
"build": "yarn build:server && yarn build:payload",
8
"serve": "PAYLOAD_CONFIG_PATH=dist/payload.config.js NODE_ENV=production node dist/server.js"
9
},
10
}

To support Windows environments consider adding the cross-env package as a devDependency and use it in scripts before setting variables.

The first script uses Payload's generate:types command in order to automatically generate TypeScript types for each of your collections and globals automatically. You can run this command whenever you need to regenerate your types, and then you can use these types in your Payload code directly.

The next script is to execute nodemon, which will read the nodemon.json config that we've written and execute our /src/server.ts script, which fires up Payload in development mode.

The following three scripts are how we will prepare Payload's admin panel for production as well as how to compile the server's TypeScript code into regular JS to use in production.

Finally, we have a serve script which is used to serve our app in production mode once it's built.

Firing it up

We're ready to go! Run yarn dev in the root of your folder to start up Payload. Then, visit http://localhost:3000/admin to create your first user and sign into the admin panel.

Generating Payload types

Now that we've got a server generated, let's try and generate some types. Run the following command to automatically generate a file that contains an interface for the default Users collection and our simple Posts collection:

1
yarn generate:types

Then check out the file that was created at /src/generated-types.ts. You can import these types in your own code to do some pretty awesome stuff.

Testing with Jest

Now it's time to get some tests written. There are a ton of different approaches to testing, but we're going to go straight for end-to-end tests. We'll use Jest to write our tests, and set up a fully functional Express server before we start our tests so that we can test against something that's as close to production as possible.

We'll also use mongodb-memory-server to connect to for all tests, so that we don't have to clutter up our development database with testing documents. This is great, because our tests will be totally controlled and isolated, but coverage will be incredibly thorough due to how we'll be testing the full API from top to bottom.

Payload will automatically attempt to use mongodb-memory-server if two conditions are met:

  1. It is locally installed in your project
  2. NODE_ENV is equal to test

Adding and configuring test dependencies

OK. Let's install all the testing dependencies we'll need:

1
yarn add --dev jest mongodb-memory-server babel-jest @babel/core @babel/preset-env @babel/preset-typescript isomorphic-fetch @types/jest

Now let's add two new config files. First, babel.config.js:

1
module.exports = {
2
presets: [
3
['@babel/preset-env', { targets: { node: 'current' } }],
4
'@babel/preset-typescript',
5
'@babel/preset-react',
6
],
7
};

We use Babel so we can write tests in TypeScript, and test full React components.

Next, jest.config.js:

1
module.exports = {
2
verbose: true,
3
testEnvironment: 'node',
4
globalSetup: '<rootDir>/src/tests/globalSetup.ts',
5
roots: ['<rootDir>/src/'],
6
};

Global Test Setup

A sharp eye might find that we're using a globalSetup file in jest.config.js to scaffold our project before any of the real magic starts. Let's add that file:

src/tests/globalSetup.ts:

1
import '../server';
2
import { resolve } from 'path';
3
import testCredentials from './credentials';
4
5
require('dotenv').config({
6
path: resolve(__dirname, '../.env'),
7
});
8
9
const { PAYLOAD_PUBLIC_SERVER_URL } = process.env;
10
11
const globalSetup = async (): Promise<void> => {
12
const response = await fetch(`${PAYLOAD_PUBLIC_SERVER_URL}/api/users/first-register`, {
13
body: JSON.stringify({
14
email: testCredentials.email,
15
password: testCredentials.password,
16
}),
17
headers: {
18
'Content-Type': 'application/json',
19
},
20
method: 'post',
21
});
22
23
const data = await response.json();
24
25
if (!data.user || !data.user.token) {
26
throw new Error('Failed to register first user');
27
}
28
};
29
30
export default globalSetup;

In this file, we're performing the following actions before our tests are executed:

  1. Importing the server, which will boot up Express and Payload using mongodb-memory-server
  2. Loading our .env file
  3. Registering a first user so that we can authenticate in our tests

You'll notice we are importing testCredentials from next to our globalSetup file. Because our Payload API will require authentication for many of our tests, and we're creating that user in our globalSetup file, we will want to reuse our user credentials in other tests to ensure we can authenticate as the newly created user. Let's create a reusable file to store our user's credentials:

src/tests/credentials.ts:

1
export default {
2
email: 'test@test.com',
3
password: 'test',
4
}

Our first test

Now that we've got our global setup in place, we can write our first test.

Add a file called src/tests/login.spec.ts:

1
import { User } from '../generated-types';
2
import testCredentials from './credentials';
3
4
require('isomorphic-fetch');
5
6
describe('Users', () => {
7
it('should allow a user to log in', async () => {
8
const result: {
9
token: string
10
user: User
11
} = await fetch(`${process.env.PAYLOAD_PUBLIC_SERVER_URL}/api/users/login`, {
12
method: 'post',
13
headers: {
14
'Content-Type': 'application/json',
15
},
16
body: JSON.stringify({
17
email: testCredentials.email,
18
password: testCredentials.password,
19
}),
20
}).then((res) => res.json());
21
22
expect(result.token).toBeDefined();
23
});
24
});
25

The test above is written in TypeScript and imports our auto-generated User TypeScript interface to properly type the fetch response that is returned from Payload's login REST API.

It will expect that a token is returned from the response.

Running tests

The last step is to add a script to execute our tests. Let's add a new line to our package.json scripts property:

1
"test": "jest --forceExit --detectOpenHandles"

Now, we can run yarn test to see a successful test!

Debugging with VSCode

Debugging can be an absolutely invaluable tool to developers working on anything more complex than a simple app. It can be difficult to understand how to set up, but once you have it configured properly, a proper debugging workflow can be significantly more powerful than just relying on console.log all the time.

You can debug your application itself, and you can even debug your tests to troubleshoot any tests that might fail in the future. Let's see how to set up VSCode to debug our new Typescript app and its tests.

First, create a new folder within your project root called .vscode. Then, add a launch.json within that folder, containing the following configuration:

./.vscode/launch.json:

1
{
2
"version": "0.2.0",
3
"configurations": [
4
{
5
"type": "node",
6
"request": "launch",
7
"name": "Launch Program",
8
"env": {
9
"PAYLOAD_CONFIG_PATH": "src/payload.config.ts",
10
},
11
"program": "${workspaceFolder}/src/server.ts",
12
},
13
{
14
"name": "Debug Jest Tests",
15
"type": "node",
16
"request": "launch",
17
"runtimeArgs": [
18
"--inspect-brk",
19
"${workspaceRoot}/node_modules/.bin/jest",
20
"--runInBand"
21
],
22
"env": {
23
"PAYLOAD_CONFIG_PATH": "src/payload.config.ts"
24
},
25
}
26
]
27
}
28

The file above includes two configurations. The first is to be able to debug your Express + Payload app itself, including any files you've imported within your Payload config. The second debug config is to be able to set breakpoints and debug directly within your Jest testing suite.

To debug, you can set breakpoints right in your code by clicking to the left of the line numbers. A breakpoint will be set and show as a red circle. When VSCode executes your scripts, it will pause at the breakpoint(s) you set and allow you to inspect the value of all variables, where your function(s) have been called from, and much more.

To start the debugger, click the "Run and Debug" sidebar icon in VSCode, choose the debugger you want to start, and click the "Play" button. If you've placed breakpoints, VSCode will automatically pause when it reaches your breakpoint.

Here is an example of a breakpoint being hit within our src/server.ts file:

Breakpoint Example Screenshot

Here is a screenshot of a breakpoint being hit within our login.spec.ts test:

Jest Breakpoint Screenshot

Debugging can be an invaluable tool to you as a developer. Setting it up early in your project will pay dividends over time as your project gets more complex, and it will help you understand how your project works to an extremely fine degree.

Conclusion

With all of the above pieces in place, you have a modern and well-equipped dev environment that you can use to build out Payload into anything you can think of - be it an API to power a web appnative app, or just a headless CMS to power a website.

You can find the code for this guide here. Let us know what you think!

Star us on GitHub

If you haven't already, stop by GitHub and give us a star by clicking on the "Star" button in the top-right corner of our repo. With our inclusion into YC and our move to open-source, we're looking to dramatically expand our community and we can't do it without you.

Join our community on Discord

We've recently started a Discord community for the Payload community to interact in realtime. Often, Discord will be the first to hear about announcements like this move to open-source, and it can prove to be a great resource if you need help building with Payload. Click here to join!