In the first part of this tutorial, we discovered how to set up a base express typescript application. In this part, we will look at how to set up environment variables, which is a great way of storing sensitive information like API keys. This is a special file ending with the .env extension that is excluded from git so as to not expose your sensitive file to the world.
To begin with, we install a special library called dotenv that is able to read from this file and make it available to the server via process.env.* We install this library by typing in our console:
npm install --save dotenv
Dotenv ships with its own types so there is no need to create one ourselves. We configure dotenv in our application by adding the following line on top of our index.ts file
import 'dotenv/config';
Our index.ts file should now look like the following
import 'dotenv/config';
import * as express from 'express';
const app = express();
//configure application routes
//@GET - dummy api route
//@ts-ignore
app.get('/api', (req, res, next) => {
res.status(200).json({
hello: 'World!',
});
});
const port: Number = Number(process.env.PORT) || 3000;
const startServer = async () => {
await app.listen(port, () => {
console.log(`
Server running on http://localhost:${port}
`);
});
};
startServer();
This configures our application to read from the .env file, which is yet to be created. In the root of your application, create a new file called .env. To test, we add a port variable and change it to 7777 as shown
PORT=7777
After restarting our server, we see our application is now running on port 7777 other than the 3000 from the previous tutorial. We proceed to set up our database.
\
We install typeorm library by typing
npm install --save typeorm pg
TypeOrm just like dotenv also ships with its own types as it is developed in typescript, the pg library helps typeorm connect to our database which is PostgreSQL in this case. In the root of our application, we create a file called ormconfig.json, this file will be used by typeorm to connect to the database. We specify the database configuration as follows, feel free to change and put ur own values inside
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "postgres",
"password": "postgres",
"database": "express_typescript",
"synchronize": true,
"logging": true,
"entities": ["src/entities/**/*.ts", "dist/entities/**/*.js"]
}
Make sure to create the database first using either the psql shell or any gui tool of your choice. The file also specifies that all our database entities will be in the entities folder inside the src file, or inside the entities in the dist folder after the typescript is transpiled.
The synchronize: true, tells TypeOrm to use our entities to create tables inside the specified database. This is very helpful as we get to create tables and interact with the database directly in typescript without actually touching any SQL code.
We then create a ts file called database.ts to use to establish the connection. We add the following code to it
import { createConnection } from 'typeorm';
export const connectDB = async () => {
await createConnection();
};
We finally let our main index.ts file know of this so a connection can be made to the database. We import it inside the index.ts and run it, our index.ts file should finally look like this
import 'dotenv/config';
import * as express from 'express';
import { connectDB } from './database'
const app = express();
//configure application routes
//@GET - dummy api route
//@ts-ignore
app.get('/api', (req, res, next) => {
res.status(200).json({
hello: 'World!',
});
});
const port: Number = Number(process.env.PORT) || 3000;
const startServer = async () => {
await app.listen(port, () => {
console.log(`
Server running on http://localhost:${port}
`);
});
};
(async () => {
await connectDB();
await startServer();
})();
That is it, run your server with npm run start:dev and see some database log information meaning a successful connection has been made to the database. Read more about TypeOrm here.Thanks for reading and don’t forget to share.
Top comments (1)
Great introduction ! To quick start a project using Typescript / Express / Typeorm, this package can help: github.com/konfer-be/ts-express-ty...