A road to the easiest user authentication system for Node.js
Tags: javascript, typescript, nextjs, nestjs
Published: 2018-12-15 11:22:35

---
title: A road to the easiest user authentication system for Node.js
published: true
description: An easiest web app template on top of nest, TypeORM, Next.js and Material UI.
tags: javascript,typescript,nextjs,nestjs
---

JavaScript is easy to read and write, but sometimes we are facing difficulties like **user authentication**.

Before talking about user authentication deeper, let me introduce you what I made this weekend:

{% github: https://github.com/saltyshiomix/ark %}

Yes, this is a super duper simple user authentication system :)

On the other hand, it uses these technologies:

- Hot reloading for the developer experience :)
    - [nodemon](https://nodemon.io/) - Monitor for any changes in your node.js application and automatically restart the server
    - [Next.js](https://nextjs.org/) - The React Framework
- Lang
    - [TypeScript](https://www.typescriptlang.org/) - Javascript that scales
- Database
    - [PostgreSQL](https://www.postgresql.org/) - The World's Most Advanced Open Source Relational Database
- ORM (Object-relational mapping)
    - [TypeORM](http://typeorm.io/) - ORM for TypeScript and JavaScript (ES7, ES6, ES5)
- Server
    - [nest](https://nestjs.com/) - A progressive Node.js framework for building efficient, reliable and scalable server-side applications
        - internally using [Express](https://expressjs.com/) - Fast, unopinionated, minimalist web framework for Node.js
    - [Next.js](https://nextjs.org/) - The React Framework
- Environment variables
    - [dotenv](https://github.com/motdotla/dotenv/) - Loads environment variables from .env for nodejs projects
- User authentication
    - [Passport](http://www.passportjs.org/) - Simple, unobtrusive authentication for Node.js
- UI framework
    - [React](https://reactjs.org/) - A JavaScript library for building user interfaces
    - [Next.js](https://nextjs.org/) - The React Framework
    - [Material UI](https://material-ui.com/) - React components that implement Google's Material Design.

So many libraries, right? Easiest authentication?

Yes.

Let's digging deeper:

## Fun Database

Thanks to [TypeORM](http://typeorm.io/), we can **synchronize database with entities**.

Here is a `user.entity.ts`:

```js
import {
  Entity,
  Column,
  PrimaryGeneratedColumn
} from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column('varchar')
  name: string;

  @Column('varchar', {
    unique: true
  })
  email: string;

  @Column('varchar')
  password: string;  
}
```

TypeORM automatically synchronize database from `@Entity()` decorator information.
In other words, database automatically changes as soon as you save `user.entity.ts`.

## Fun Coding

With [nest](https://nestjs.com/), we can use modern JavaScript(TypeScript), and with [VSCode](https://code.visualstudio.com/) we can obtain the maximum benefit like code intelligence.

Here is a sample `users.controller.ts`:

```js
import {
  Controller,
  Get
} from '@nestjs/common';
import { User } from './user.entity';
import { UsersService } from './users.service';

@Controller('api/users')
export class UsersController {
  constructor(private readonly service: UsersService) {}

  @Get()
  async findAll(@Query() query): Promise<User[]> {
    return await this.service.findAll();
  }
}
```

By constructor injection, `users.controller.ts` doesn't care about how to `findAll()` users.

And `users.service.ts` is like this:

```js
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UsersService {
  constructor(@InjectRepository(User) private readonly repository: Repository<User>) {}

  async findAll(): Promise<User[]> {
    return await this.repository.find();
  }
}
```

Can you believe this?

We can `findAll()` users without coding SQL scripts because [TypeORM](http://typeorm.io/) and [nest](https://nestjs.com/) conceal implementation. (so called "Repository Pattern")

## Fun SEO (Server Side Rendering)

[Next.js](https://nextjs.org/) enables us to write `page/index.tsx` without caring about server side rendering:

```js
export default () => 'Hello SSR!'; // this is a React.Component :)
```

## How to try [ARK](https://github.com/saltyshiomix/ark)

First, you need to install [PostgreSQL](https://www.postgresql.org/).

If you use Mac and [Homebrew](https://brew.sh/), setup is so easy:

```bash
# install database (postgresql)
$ brew install postgresql

# if you want to start postgresql in startup, try do this
$ brew services start postgresql

# create user "arkuser" with password "arkark"
$ createuser -P arkuser

# create database "arkdb" owened by "arkuser"
$ createdb arkdb -O arkuser
```

That's it!

And use it like [Next.js](https://nextjs.org/):

```bash
# clone repository
$ git clone https://github.com/saltyshiomix/ark.git

# install dependencies
$ cd ark
$ yarn

# development mode
# please make sure to create the `.env` file!
$ yarn dev

# production mode
# please make sure to create the `.next/.env` file!
$ yarn build
$ yarn start
```

(`.env` file is like this:)

```
# DB
DB_TYPE=postgres
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=arkuser
DB_PASSWORD=arkark
DB_DATABASE=arkdb
DB_SYNCHRONIZE=true

# App
HOST=localhost
PORT=4000
SESSION_SECRET=ark
```

And you'll see `http://localhost:4000`:

![login screen](https://thepracticaldev.s3.amazonaws.com/i/1et6gurxpen3rayyemde.png)

And create an account:

![signup screen](https://thepracticaldev.s3.amazonaws.com/i/wl7lu3mrp936h5efe3d0.png)

You are now logged in!

![logged-in screen](https://thepracticaldev.s3.amazonaws.com/i/6ctnbaspwed60ehdp8q1.png)

## Conclusion

I created [ARK](https://github.com/saltyshiomix/ark) repository for the purpose of showing how to implement user authentication system easily.

So PRs are welcome!
(like "Implement social login", "Implement JSON API" and so on.)

I hope you helped :)