<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by ZEYNAL ALAKUŞ on Medium]]></title>
        <description><![CDATA[Stories by ZEYNAL ALAKUŞ on Medium]]></description>
        <link>https://medium.com/@zeynal.a2907?source=rss-fdf85c0c6364------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qZfyN2Z5CMIbTBrk.jpg</url>
            <title>Stories by ZEYNAL ALAKUŞ on Medium</title>
            <link>https://medium.com/@zeynal.a2907?source=rss-fdf85c0c6364------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:09:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zeynal.a2907/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Nest Auth App with JWT Strategy, Docker and Typeorm(Postgresql)]]></title>
            <link>https://medium.com/@zeynal.a2907/nest-auth-app-with-jwt-strategy-docker-and-typeorm-postgresql-c791d8e3718a?source=rss-fdf85c0c6364------2</link>
            <guid isPermaLink="false">https://medium.com/p/c791d8e3718a</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <dc:creator><![CDATA[ZEYNAL ALAKUŞ]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 09:16:38 GMT</pubDate>
            <atom:updated>2023-07-07T09:18:46.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*q3n15llxO-XnTdav.png" /></figure><h3>1. Creating the App</h3><pre>nest new nest-jwt-auth</pre><h3>2. Docker Configuration</h3><h4>2. 1. Creating docker-compose.yml and docker.env files</h4><pre>// docker.env<br><br>POSTGRES_USER=admin<br>POSTGRES_PASSWORD=admin<br>POSTGRES_DB=nestjs</pre><pre>// docker-compose.yml<br><br>version: &#39;3&#39;<br>services:<br>  postgres:<br>    container_name: postgres<br>    image: postgres:latest<br>    ports:<br>      - &#39;5432:5432&#39;<br>    volumes:<br>      - /var/folders/postgres:/data/postgres<br>    env_file:<br>      - docker.env<br>    networks:<br>      - postgres<br><br>networks:<br>  postgres:<br>    driver: bridge</pre><h4>2. 2. Running docker image (terminal)</h4><pre>docker-compose up</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMVUMEkiHPm1H4COQ5pjzA.png" /></figure><h3>3. Database Connection</h3><h4>3. 1. Creating .env file in root folder</h4><pre>// .env<br><br>POSTGRES_HOST=localhost<br>POSTGRES_PORT=5432<br>POSTGRES_USER=admin<br>POSTGRES_PASSWORD=admin<br>POSTGRES_DB=nestjs</pre><h4>3. 2. Installing typeorm libraries, pg for postgresql and @nestjs/config to get env properties(terminal)</h4><pre>npm i @nestjs/typeorm typeorm pg @nestjs/config</pre><h4>3. 3. Adding database configuration in app.module.ts</h4><pre>// app.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { ConfigModule, ConfigService } from &quot;@nestjs/config&quot;;<br>import { TypeOrmModule } from &quot;@nestjs/typeorm&quot;;<br><br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({<br>      envFilePath: &#39;.env&#39;<br>    }),<br>    TypeOrmModule.forRootAsync({<br>      imports: [ConfigModule],<br>      inject: [ConfigService],<br>      useFactory: (configService: ConfigService) =&gt; {<br>        return {<br>          type: &#39;postgres&#39;,<br>          host: configService.get(&#39;POSTGRES_HOST&#39;),<br>          port: Number(configService.get(&#39;POSTGRES_PORT&#39;)),<br>          username: configService.get(&#39;POSTGRES_USER&#39;),<br>          password: configService.get(&#39;POSTGRES_PASSWORD&#39;),<br>          database: configService.get(&#39;POSTGRES_DB&#39;),<br>          entities: [__dirname + &#39;/../**/*.entity.js&#39;] ,<br>          synchronize: true<br>        }<br>      }<br>    })<br>  ],<br>  controllers: [],<br>  providers: [],<br>})<br>export class AppModule {}</pre><h4>3. 4. Run the app to check for the errors (terminal)</h4><pre>npm run start:dev</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kflVWsNdByvhmLoqNM2Fgw.png" /></figure><h3>4. Auth Module and User Registration Functionality</h3><h4>4. 1. Generation Auth module (terminal)</h4><pre>nest g module auth</pre><h4>4. 2. Creating user entity in Auth folder and updating auth.module.ts</h4><pre>// auth/user.entity.ts<br><br>import { Column, Entity, PrimaryGeneratedColumn } from &quot;typeorm&quot;;<br><br>@Entity(&#39;users&#39;)<br>export class User {<br>  @PrimaryGeneratedColumn()<br>  id: string;<br>  <br>  @Column({unique: true})<br>  email: string;<br>  <br>  @Column()<br>  password: string;<br>}</pre><pre>// auth/auth.module.ts<br><br>import { Module } from &quot;@nestjs/common&quot;;<br>import { TypeOrmModule } from &quot;@nestjs/typeorm&quot;;<br>import { User } from &quot;./user.entity&quot;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forFeature([User])<br>  ]<br>})<br>export class AuthModule {}</pre><h4>4. 3. Installing class-validator and class-transformer to use dto and validate it</h4><pre>// terminal<br><br>npm i class-validator class-transformer</pre><pre>// main.ts<br><br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import { ValidationPipe } from &quot;@nestjs/common&quot;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  app.useGlobalPipes(new ValidationPipe())<br>  await app.listen(3000);<br>}<br>bootstrap();</pre><pre>// create-user.dto<br><br>import { IsEmail, IsNotEmpty, IsString, MaxLength, MinLength } from &quot;class-validator&quot;;<br><br>export class CreateUserDto {<br>  @IsEmail()<br>  @IsNotEmpty()<br>  email: string;<br>  <br>  @IsString()<br>  @MinLength(8)<br>  @MaxLength(60)<br>  password: string;<br>}</pre><h4>4. 4. Creating Auth Service to handle registration requests</h4><pre>// auth/auth.service.ts<br><br>import { BadRequestException, Injectable } from &quot;@nestjs/common&quot;;<br>import { InjectRepository } from &quot;@nestjs/typeorm&quot;;<br>import { User } from &quot;./user.entity&quot;;<br>import { Repository } from &quot;typeorm&quot;;<br>import { randomBytes, scrypt as _scrypt } from &quot;crypto&quot;;<br>import { CreateUserDto } from &quot;./create-user.dto&quot;;<br>import { promisify } from &quot;util&quot;;<br><br>const scrypt = promisify(_scrypt);<br><br>@Injectable()<br>export class AuthService {<br>  constructor(@InjectRepository(User) private userRepository: Repository&lt;User&gt;) {<br>  }<br><br><br>  async register(createUserDto: CreateUserDto) {<br>    const {email, password} = createUserDto;<br>    <br>    // checking user already exists or not<br>    const user = await this.userRepository.findOne({where: {email}});<br>    if (user) {<br>      throw new BadRequestException(&#39;User Already Exists&#39;)<br>    }<br>    <br>    // hashing the password with salt<br>    const salt = randomBytes(8).toString(&#39;hex&#39;);<br>    const hash = (await scrypt(password, salt, 32)) as Buffer;<br>    const hashedPassword = salt + &#39;.&#39; + hash.toString(&#39;hex&#39;);<br>    <br>    // saving the user<br>    const newUser = this.userRepository.create({email, password: hashedPassword});<br>    await this.userRepository.save(newUser);<br>  }<br>}</pre><h4>4. 5. Creating Auth Controller to get register requester and redirect them to auth service</h4><pre>// auth/auth.controller.ts<br><br>import { Body, Controller, Post } from &quot;@nestjs/common&quot;;<br>import { AuthService } from &quot;./auth.service&quot;;<br>import { CreateUserDto } from &quot;./create-user.dto&quot;;<br><br>@Controller(&#39;auth&#39;)<br>export class AuthController {<br>  constructor(private readonly authService: AuthService) {<br>  }<br>  <br>  // ..../auth/register<br>  @Post(&#39;register&#39;)<br>  async register(@Body() createUserDto: CreateUserDto) {<br>    await this.authService.register(createUserDto);<br>  }<br>}</pre><h4>4. 6. Adding Auth Controller and Service to Auth Module</h4><pre>// auth/auth.module.ts<br><br>import { Module } from &quot;@nestjs/common&quot;;<br>import { TypeOrmModule } from &quot;@nestjs/typeorm&quot;;<br>import { User } from &quot;./user.entity&quot;;<br>import { AuthController } from &quot;./auth.controller&quot;;<br>import { AuthService } from &quot;./auth.service&quot;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forFeature([User])<br>  ],<br>  controllers: [AuthController],<br>  providers: [AuthService]<br>})<br>export class AuthModule {}</pre><h4>4. 7. Adding Auth Module to App Module</h4><pre>// app.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { ConfigModule, ConfigService } from &quot;@nestjs/config&quot;;<br>import { TypeOrmModule } from &quot;@nestjs/typeorm&quot;;<br>import { AuthModule } from &quot;./auth/auth.module&quot;;<br><br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({<br>      envFilePath: &#39;.env&#39;<br>    }),<br>    TypeOrmModule.forRootAsync({<br>      imports: [ConfigModule],<br>      inject: [ConfigService],<br>      useFactory: (configService: ConfigService) =&gt; {<br>        return {<br>          type: &#39;postgres&#39;,<br>          host: configService.get(&#39;POSTGRES_HOST&#39;),<br>          port: Number(configService.get(&#39;POSTGRES_PORT&#39;)),<br>          username: configService.get(&#39;POSTGRES_USER&#39;),<br>          password: configService.get(&#39;POSTGRES_PASSWORD&#39;),<br>          database: configService.get(&#39;POSTGRES_DB&#39;),<br>          entities: [__dirname + &#39;/../**/*.entity.js&#39;] ,<br>          synchronize: true<br>        }<br>      }<br>    }),<br>    AuthModule<br>  ],<br>  controllers: [],<br>  providers: [],<br>})<br>export class AppModule {}</pre><h4>4. 8. Testing Registration with Postman</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvWZ2K1MgsW5m6N4DTU4kA.png" /></figure><h3>5. Local Strategy and JWT Strategy</h3><p>Local strategy will be used with login requests to get the email and password and validate the user. Login requests will return access_token.</p><p>JWT strategy will be used with the requests which need to be protected. JWT strategy will check whether there is a token in the header of the requests and if there is, it will validate it.</p><h4>5. 1. Installing required libraries</h4><pre>// terminal<br><br>npm install --save @nestjs/passport passport passport-local @nestjs/jwt passport-jwt</pre><pre>// terminal<br><br>npm install --save-dev @types/passport-jwt @types/passport-local</pre><h4>5. 2. Adding validateUser function in Auth Service</h4><pre>// auth/auth.service.ts<br><br>import { BadRequestException, Injectable } from &quot;@nestjs/common&quot;;<br>import { InjectRepository } from &quot;@nestjs/typeorm&quot;;<br>import { User } from &quot;./user.entity&quot;;<br>import { Repository } from &quot;typeorm&quot;;<br>import { randomBytes, scrypt as _scrypt } from &quot;crypto&quot;;<br>import { CreateUserDto } from &quot;./create-user.dto&quot;;<br>import { promisify } from &quot;util&quot;;<br><br>const scrypt = promisify(_scrypt);<br><br>@Injectable()<br>export class AuthService {<br>  constructor(@InjectRepository(User) private userRepository: Repository&lt;User&gt;) {<br>  }<br><br><br>  async register(createUserDto: CreateUserDto) {<br>    const {email, password} = createUserDto;<br><br>    // checking user already exists or not<br>    const user = await this.userRepository.findOne({where: {email}});<br>    if (user) {<br>      throw new BadRequestException(&#39;User Already Exists&#39;)<br>    }<br><br>    // hashing the password with salt<br>    const salt = randomBytes(8).toString(&#39;hex&#39;);<br>    const hash = (await scrypt(password, salt, 32)) as Buffer;<br>    const hashedPassword = salt + &#39;.&#39; + hash.toString(&#39;hex&#39;);<br><br>    // saving the user<br>    const newUser = this.userRepository.create({email, password: hashedPassword});<br>    await this.userRepository.save(newUser);<br>  }<br><br>  async validateUser(email: string, password: string) {<br>    const user = await this.userRepository.findOne({where: {email}});<br>    if (user) {<br>      const [salt, hashedPassword] = user.password.split(&#39;.&#39;);<br><br>      const controlHashedPassword = (await scrypt(password, salt, 32)) as Buffer;<br>      if (hashedPassword === controlHashedPassword.toString(&#39;hex&#39;)) {<br>        return user;<br>      }<br>    }<br>    return null;<br>  }<br><br>}</pre><h4>5. 3. Creating Local Strategy</h4><pre>// auth/strategy/local.strategy.ts<br><br>import { BadRequestException, Injectable } from &quot;@nestjs/common&quot;;<br>import { PassportStrategy } from &quot;@nestjs/passport&quot;;<br>import { Strategy } from &quot;passport-local&quot;;<br>import { AuthService } from &quot;../auth.service&quot;;<br><br>@Injectable()<br>export class LocalStrategy extends PassportStrategy(Strategy) {<br>  constructor(private readonly authService: AuthService) {<br>    super({<br>      // this assignment is to use email instead of username while validating<br>      usernameField: &#39;email&#39;<br>    });<br>  }<br>  <br>  async validate(email: string, password: string) {<br>    const user = await this.authService.validateUser(email, password);<br>    if (!user) {<br>      throw new BadRequestException(&#39;Wrong Credentials&#39;);<br>    }<br>    return user;<br>  }<br>}</pre><pre>// auth/guard/local.guard.ts<br><br>import { Injectable } from &quot;@nestjs/common&quot;;<br>import { AuthGuard } from &quot;@nestjs/passport&quot;;<br><br>@Injectable()<br>export class LocalGuard extends AuthGuard(&#39;local&#39;) {}</pre><pre>// auth/auth.module.ts<br><br>import { Module } from &quot;@nestjs/common&quot;;<br>import { TypeOrmModule } from &quot;@nestjs/typeorm&quot;;<br>import { User } from &quot;./user.entity&quot;;<br>import { AuthController } from &quot;./auth.controller&quot;;<br>import { AuthService } from &quot;./auth.service&quot;;<br>import { LocalStrategy } from &quot;./strategy/local.strategy&quot;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forFeature([User])<br>  ],<br>  controllers: [AuthController],<br>  providers: [AuthService, LocalStrategy]<br>})<br>export class AuthModule {}</pre><h4>5. 4. Using Local Strategy and Guard to get the user and return access_token from the auth service</h4><pre>// auth/auth.controller.ts<br><br>import { Body, Controller, Post, Request, UseGuards } from &quot;@nestjs/common&quot;;<br>import { AuthService } from &quot;./auth.service&quot;;<br>import { CreateUserDto } from &quot;./create-user.dto&quot;;<br>import { LocalGuard } from &quot;./guard/local.guard&quot;;<br><br>@Controller(&#39;auth&#39;)<br>export class AuthController {<br>  constructor(private readonly authService: AuthService) {<br>  }<br><br>  // ..../auth/register<br>  @Post(&#39;register&#39;)<br>  async register(@Body() createUserDto: CreateUserDto) {<br>    await this.authService.register(createUserDto);<br>  }<br><br>  // ..../auth/login<br>  @Post(&#39;login&#39;)<br>  @UseGuards(LocalGuard)<br>  login(@Request() req) {<br>    return this.authService.login(req.user);<br>  }<br>}</pre><pre>// auth/auth.service.ts<br><br>import { BadRequestException, Injectable } from &quot;@nestjs/common&quot;;<br>import { InjectRepository } from &quot;@nestjs/typeorm&quot;;<br>import { User } from &quot;./user.entity&quot;;<br>import { Repository } from &quot;typeorm&quot;;<br>import { randomBytes, scrypt as _scrypt } from &quot;crypto&quot;;<br>import { CreateUserDto } from &quot;./create-user.dto&quot;;<br>import { promisify } from &quot;util&quot;;<br>import { JwtService } from &quot;@nestjs/jwt&quot;;<br><br>const scrypt = promisify(_scrypt);<br><br>@Injectable()<br>export class AuthService {<br>  constructor(@InjectRepository(User) private userRepository: Repository&lt;User&gt;, private jwtService: JwtService) {<br>  }<br><br><br>  async register(createUserDto: CreateUserDto) {<br>    const {email, password} = createUserDto;<br><br>    // checking user already exists or not<br>    const user = await this.userRepository.findOne({where: {email}});<br>    if (user) {<br>      throw new BadRequestException(&#39;User Already Exists&#39;)<br>    }<br><br>    // hashing the password with salt<br>    const salt = randomBytes(8).toString(&#39;hex&#39;);<br>    const hash = (await scrypt(password, salt, 32)) as Buffer;<br>    const hashedPassword = salt + &#39;.&#39; + hash.toString(&#39;hex&#39;);<br><br>    // saving the user<br>    const newUser = this.userRepository.create({email, password: hashedPassword});<br>    await this.userRepository.save(newUser);<br>  }<br><br>  async validateUser(email: string, password: string) {<br>    const user = await this.userRepository.findOne({where: {email}});<br>    if (user) {<br>      const [salt, hashedPassword] = user.password.split(&#39;.&#39;);<br><br>      const controlHashedPassword = (await scrypt(password, salt, 32)) as Buffer;<br>      if (hashedPassword === controlHashedPassword.toString(&#39;hex&#39;)) {<br>        return user;<br>      }<br>    }<br>    return null;<br>  }<br><br>  login(user: User) {<br>    const payload = {sub: user.id, email: user.email};<br>    return {<br>      access_token: this.jwtService.sign(payload)<br>    }<br>  }<br>}</pre><pre>// auth/constants/jwt-constants.ts<br><br>export const secretKey = &#39;someRandomSecretKey&#39;</pre><pre>// auth/auth.module.ts<br><br>import { Module } from &quot;@nestjs/common&quot;;<br>import { TypeOrmModule } from &quot;@nestjs/typeorm&quot;;<br>import { User } from &quot;./user.entity&quot;;<br>import { AuthController } from &quot;./auth.controller&quot;;<br>import { AuthService } from &quot;./auth.service&quot;;<br>import { LocalStrategy } from &quot;./strategy/local.strategy&quot;;<br>import { JwtModule } from &quot;@nestjs/jwt&quot;;<br>import { secretKey } from &quot;./constants/jwt-constants&quot;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forFeature([User]),<br>    JwtModule.register({<br>      secret: secretKey,<br>      signOptions: {expiresIn: &#39;1h&#39;}<br>    })<br>  ],<br>  controllers: [AuthController],<br>  providers: [AuthService, LocalStrategy]<br>})<br>export class AuthModule {}</pre><h4>5. 5. Testing Local Strategy and Login with Postman</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwp81ETmf9cVwUG4dqa8Eg.png" /></figure><h4>5. 6. Creating JWT Strategy</h4><pre>// auth/strategy/jwt.strategy.ts<br><br>import { Injectable } from &quot;@nestjs/common&quot;;<br>import { PassportStrategy } from &quot;@nestjs/passport&quot;;<br>import { ExtractJwt, Strategy } from &quot;passport-jwt&quot;;<br>import { secretKey } from &quot;../constants/jwt-constants&quot;;<br><br>@Injectable()<br>export class JwtStrategy extends PassportStrategy(Strategy) {<br>  constructor() {<br>    super({<br>      secretOrKey: secretKey,<br>      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),<br>      ignoreExpiration: false<br>    });<br>  }<br><br>  validate(payload: {sub: string, email: string}) {<br>    return {id: payload.sub, email: payload.email}<br>  }<br>}</pre><pre>// auth/guard/jwt.guard.ts<br><br>import { Injectable } from &quot;@nestjs/common&quot;;<br>import { AuthGuard } from &quot;@nestjs/passport&quot;;<br><br>@Injectable()<br>export class JwtGuard extends AuthGuard(&#39;jwt&#39;) {}</pre><pre>// auth/auth.module.ts<br><br>import { Module } from &quot;@nestjs/common&quot;;<br>import { TypeOrmModule } from &quot;@nestjs/typeorm&quot;;<br>import { User } from &quot;./user.entity&quot;;<br>import { AuthController } from &quot;./auth.controller&quot;;<br>import { AuthService } from &quot;./auth.service&quot;;<br>import { LocalStrategy } from &quot;./strategy/local.strategy&quot;;<br>import { JwtModule } from &quot;@nestjs/jwt&quot;;<br>import { secretKey } from &quot;./constants/jwt-constants&quot;;<br>import { JwtStrategy } from &quot;./strategy/jwt.strategy&quot;;<br>import { PassportModule } from &quot;@nestjs/passport&quot;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forFeature([User]),<br>    PassportModule,<br>    JwtModule.register({<br>      secret: secretKey,<br>      signOptions: {expiresIn: &#39;1h&#39;}<br>    })<br>  ],<br>  controllers: [AuthController],<br>  providers: [AuthService, LocalStrategy, JwtStrategy]<br>})<br>export class AuthModule {}</pre><h3>5. 7. Using Jwt Guard for one of the requests</h3><pre>// auth/auth.controller.ts<br><br>import { Body, Controller, Get, Post, Request, UseGuards } from &quot;@nestjs/common&quot;;<br>import { AuthService } from &quot;./auth.service&quot;;<br>import { CreateUserDto } from &quot;./create-user.dto&quot;;<br>import { LocalGuard } from &quot;./guard/local.guard&quot;;<br>import { JwtGuard } from &quot;./guard/jwt.guard&quot;;<br><br>@Controller(&#39;auth&#39;)<br>export class AuthController {<br>  constructor(private readonly authService: AuthService) {<br>  }<br><br>  // ..../auth/register<br>  @Post(&#39;register&#39;)<br>  async register(@Body() createUserDto: CreateUserDto) {<br>    await this.authService.register(createUserDto);<br>  }<br><br>  // ..../auth/login<br>  @Post(&#39;login&#39;)<br>  @UseGuards(LocalGuard)<br>  login(@Request() req) {<br>    return this.authService.login(req.user);<br>  }<br><br>  // ..../auth/profile<br>  @Get(&#39;profile&#39;)<br>  @UseGuards(JwtGuard)<br>  profile(@Request() req) {<br>    return req.user;<br>  }<br>}</pre><h4>5. 8. Testing Jwt Token with Postman</h4><p>without token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnIn31zc_ds57AzQ1fiDPQ.png" /></figure><p>with token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IW1fxUC5M8mVbxOw2pdoBw.png" /></figure><p>The source code:</p><p><a href="https://github.com/zeynalalakus/nest-jwt-auth/tree/develop">https://github.com/zeynalalakus/nest-jwt-auth/tree/develop</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c791d8e3718a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Nodejs Backend App on Digital Ocean]]></title>
            <link>https://medium.com/@zeynal.a2907/deploy-nodejs-backend-app-on-digital-ocean-fcca5b44416c?source=rss-fdf85c0c6364------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcca5b44416c</guid>
            <category><![CDATA[deploy-yourself]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[digitalocean]]></category>
            <dc:creator><![CDATA[ZEYNAL ALAKUŞ]]></dc:creator>
            <pubDate>Sat, 12 Feb 2022 10:18:57 GMT</pubDate>
            <atom:updated>2022-02-12T10:26:28.808Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong><em>Create A Droplet</em><br></strong>In digital ocean, click on the create button and select the droplet option<br>- Choose an image (I will go with Ubuntu)<br>- Choose a plan based on your project needs<br>- Choose a datacenter region<br>- In Authentication Part, click on New SSH Key and continue with second step of this article to create an SSH Key</li><li><strong><em>Download putty.exe and puttygen.exe to generate a key, save settings and connect to the server/droplet easily later on</em></strong></li></ol><p><a href="https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html">https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.htm</a>l</p><ul><li>Run puttygen.exe to create SSH key<br>- Click on generate and move the mouse over the blank area to create some randomness</li><li>Save public key as a txt file in a safe folder</li><li>Save private key as a .ppk file in the same folder with public key</li><li>Copy public key and paste it in SSH Key Content area in digital ocean</li><li>In droplet creating page, if you need, select additional options and finalize and create the droplet.</li></ul><h3>3. <strong>Connect Via Putty</strong></h3><ul><li>Open up putty.exe</li><li>Type in your droplet ip address in <strong>Host Name </strong>field</li><li>Click on the <strong>connection-&gt;data </strong>tab and add ‘root’ in <strong>Auto-Login Username </strong>field</li><li>Click on the <strong>SSH-&gt;Auth</strong> tab and <strong>browse </strong>for your private key file (.ppk)</li><li>Go back to the <strong>session </strong>tab and give a name to the session in <strong>Saved Sessions </strong>field and click on <strong>save </strong>button.</li><li>Click on <strong>open </strong>button to connect to the server/droplet</li></ul><h3>4. <strong>Create New User and Authorize Key For New User</strong></h3><p>In terminal, write the command below to create a user with name ‘newuser’. You can write any name you want.</p><ul><li><strong><em>adduser newuser</em></strong> (create user — save password)</li><li><strong><em>usermod -aG sudo newuser</em></strong> (add the user to the sudo group)</li><li><strong><em>sudo su - newuser</em></strong> (login as the new user)</li><li><strong><em>mkdir ~/.ssh</em></strong> (create ssh directory)</li><li><strong><em>chmod 700 ~/.ssh</em></strong></li><li><strong><em>nano ~/.ssh/authorized_keys</em></strong> (open up authorized_keys file)</li><li>copy and paste your public key in form below without linebreaks<br><strong><em>ssh-rsa your-public-key</em></strong></li><li>ctrl-x -&gt; ctrl-y -&gt;enter to save file and exit</li><li><strong><em>chmod 600 ~/.ssh/authorized_keys</em></strong></li><li><strong><em>sudo service ssh restart</em></strong><br>enter your password you have created when adding new user</li><li>in putty click on session name you saved and click on <strong>load </strong>button</li><li>in <strong><em>connection-&gt;data </em></strong>tab, change <strong><em>Auto-Login Username</em></strong> to new username</li><li>go back to <strong><em>session </em></strong>tab and click on <strong><em>save </em></strong>and then <strong><em>open</em></strong></li><li>now you have logged in as a new user without entering any password</li></ul><h3>5. <strong><em>Disable Root and Password Login</em></strong></h3><ul><li><strong><em>sudo nano /etc/ssh/sshd_config</em></strong></li><li>change the following lines<br>PermitRootLogin no<br>PasswordAuthentication no</li><li>save and exit (ctrl-x&gt;ctrl-y&gt;enter)</li><li><strong><em>sudo systemctl reload sshd</em></strong> (to reload ssh with this command)</li></ul><h3>6.<strong> Install Nodejs, Npm and Git</strong></h3><ul><li><strong>sudo apt update</strong></li><li><strong>sudo apt install nodejs</strong></li><li><strong>sudo apt install npm</strong></li><li><strong>sudo apt-get install git</strong></li></ul><h3><strong>7. Github Permission and Clone the Project</strong></h3><ul><li><strong><em>ssh-keygen -t rsa -C “your github email”</em></strong> (with quotation marks to enable permission for github repo cloning)</li><li><strong><em>git clone &lt;your-github-project&gt;</em></strong></li><li><strong><em>cd your-project-directory</em></strong></li><li><strong><em>npm install</em></strong></li><li><strong><em>node server.js/index.js </em></strong>(run your node project)</li><li>you can check your app running in droplet-ip-adress:port like 123.123.12.12:5000</li><li>ctrl-c to stop running node</li><li><strong><em>sudo npm install -g pm2</em></strong> (install pm2 to run project automatically)</li><li><strong><em>pm2 start server.js/index.js</em></strong> (run project)</li><li>project has been running but on ip address. In order to run it on a domain name, you need to arrange dns settings to redirect that domain to digital ocean servers</li><li>go to your domain provider site and open up dns settings and change them like this one</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*Wt-G2UyyuZKudP8Fw0w81Q.png" /></figure><ul><li>In digital ocean, go to networking</li><li>in domain tab, enter your domain name and add it</li><li>in create new record page and <strong>A</strong> tab, enter <strong>@</strong> in <strong>hostname</strong> field and select your droplet in<strong> will direct to</strong> field and create record</li><li>in same page, go to <strong>CNAME </strong>tab, enter <strong>www </strong>in <strong>hostname </strong>field, enter <strong>@</strong> in <strong>is an alias of</strong> field and create record</li><li>now you check the domain name with port stated in project server.js/index.js file</li><li>in order to remove port part and use domain name only, apply the following steps</li><li><strong>pm2 stop server.js/index.js</strong></li><li><strong>sudo nano server.js/index.js</strong></li><li>change port to 80 and save it</li><li><strong>sudo apt-get install libcap2-bin</strong></li></ul><pre><strong>sudo setcap &#39;cap_net_bind_service=+ep&#39; `which node`</strong></pre><ul><li><strong>pm2 start server.js/index.js</strong></li></ul><p>Now it is running in the domain name you have added without port number specified.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcca5b44416c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>