<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sergey Dudik</title>
    <description>The latest articles on DEV Community by Sergey Dudik (@sergey-dudik).</description>
    <link>https://dev.to/sergey-dudik</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1235973%2Fc8c2b669-465c-411b-af30-e88ec15cb6b0.jpeg</url>
      <title>DEV Community: Sergey Dudik</title>
      <link>https://dev.to/sergey-dudik</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sergey-dudik"/>
    <language>en</language>
    <item>
      <title>Session vs. JWT: The Difference You Might Not Know</title>
      <dc:creator>Sergey Dudik</dc:creator>
      <pubDate>Fri, 03 Jan 2025 13:26:19 +0000</pubDate>
      <link>https://dev.to/sergey-dudik/session-vs-jwt-the-difference-you-might-not-know-266p</link>
      <guid>https://dev.to/sergey-dudik/session-vs-jwt-the-difference-you-might-not-know-266p</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frf4o66d30skbfdr0h94h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frf4o66d30skbfdr0h94h.png" alt="Session vs JWT" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the world of web development, managing user authentication is a critical part of creating secure and efficient applications. Two of the most commonly used methods for handling this are sessions and JSON Web Tokens (JWTs). While both serve the purpose of managing user identity and access, they do so in fundamentally different ways, each with its own strengths and weaknesses.&lt;/p&gt;

&lt;p&gt;Understanding the key differences between sessions and JWTs can help developers choose the right approach for their specific needs. Are you optimizing for scalability, security, or simplicity? Should your application store data server-side or rely on tokens for stateless communication?&lt;/p&gt;

&lt;p&gt;In this article, we’ll break down the core concepts, compare the pros and cons, and highlight scenarios where each method shines. Whether you’re a beginner looking to grasp the basics or an experienced developer seeking clarity, this guide will give you the insights you need to make informed decisions about session vs. JWT authentication.&lt;/p&gt;

&lt;h2&gt;
  
  
  Session
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr4t4md6m8kg6qmqixa4p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr4t4md6m8kg6qmqixa4p.png" alt="Session Flow" width="800" height="253"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A session is a server-side method for storing user-specific data during a user’s interaction with a web application. When a user logs in, the server generates a unique session ID, which is sent to the client (typically via cookies). The server keeps this session ID mapped to the user’s data in memory or a database.&lt;/p&gt;

&lt;p&gt;How Sessions Work:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The client logs in and sends credentials to the server.&lt;/li&gt;
&lt;li&gt;The server validates the credentials and generates a unique session.&lt;/li&gt;
&lt;li&gt;The session is stored server-side, and a corresponding cookie containing the session is sent to the client.&lt;/li&gt;
&lt;li&gt;For subsequent requests, the client sends the session cookie back to the server, which retrieves the user’s session data.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  JWT
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftyy1xzyzft0eyz9oiqzd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftyy1xzyzft0eyz9oiqzd.png" alt="JWT Flow" width="800" height="299"&gt;&lt;/a&gt;&lt;br&gt;
A JSON Web Token (JWT) is a compact, self-contained token format used for authentication and data exchange. Unlike sessions, JWTs are stateless and do not require server-side storage. The token contains encoded information (claims) about the user, such as their ID or role, which the server can decode and verify.&lt;/p&gt;

&lt;p&gt;How JWTs Work:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The client logs in and sends credentials to the server.&lt;/li&gt;
&lt;li&gt;The server validates the credentials and generates a JWT, signed using a secret or private key.&lt;/li&gt;
&lt;li&gt;The JWT is sent to the client, typically stored in localStorage, sessionStorage, or cookies.&lt;/li&gt;
&lt;li&gt;For subsequent requests, the client includes the JWT in the request header, which the server verifies to authenticate the user.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Key Differences Between Sessions and JWTs
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;+=============+===================================+========================================+
|   Feature   |              Session              |                  JWT                   |
+=============+===================================+========================================+
| Storage     | Server-side                       | Client-side                            |
+-------------+-----------------------------------+----------------------------------------+
| Scalability | Limited, requires sticky sessions | Highly scalable, stateless             |
+-------------+-----------------------------------+----------------------------------------+
| Token Size  | Lightweight (session ID only)     | Larger (includes payload, signature)   |
+-------------+-----------------------------------+----------------------------------------+
| Security    | Relies on server-side validation  | Relies on token signature verification |
+-------------+-----------------------------------+----------------------------------------+
| State       | Stateful                          | Stateless                              |
+-------------+-----------------------------------+----------------------------------------+
| Use Cases   | Ideal for traditional web apps    | Best for APIs, SPAs, and microservices |
+-------------+-----------------------------------+----------------------------------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When choosing between Sessions and JSON Web Tokens (JWTs) for authentication, it’s essential to understand a fundamental difference: how revocation and storage work. These characteristics can significantly influence your system’s architecture and security.&lt;/p&gt;

&lt;h2&gt;
  
  
  Immediate Revocation vs. Statelessness
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Session Revocation:&lt;/strong&gt; Sessions are stored server-side, meaning they can be invalidated immediately by the server. If a user logs out or an admin revokes their access, the session is immediately terminated. This makes sessions an excellent choice for applications requiring high security, as the server has full control over session lifecycle and validity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;JWT Revocation:&lt;/strong&gt; Unlike sessions, JWTs are self-contained tokens. They include all the information needed for validation (e.g., user ID, roles) and are signed by the server. Once issued, a JWT remains valid until it expires, as the server cannot directly revoke it without additional mechanisms (e.g., a blacklist or token invalidation strategy). This characteristic can pose a challenge in applications where immediate revocation is critical.&lt;/p&gt;

&lt;p&gt;Storage Requirements and Architectural Implications&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Session Storage:&lt;/strong&gt; Sessions require server-side storage, which must be accessible across all parts of the system. For example, in a microservices architecture, each service or gateway must have access to a shared session storage solution. This could be a database, an in-memory store like Redis, or another centralized storage mechanism. While this allows for better control, it adds complexity to your system and may impact scalability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;JWT Storage:&lt;/strong&gt; JWTs, being stateless, eliminate the need for server-side storage. The token is passed between the client and server, typically stored on the client side (e.g., in cookies or local storage). This simplifies architecture, particularly in distributed systems and microservices, where shared session storage can introduce bottlenecks or points of failure. However, since JWTs are self-contained, any changes to user permissions or access require additional mechanisms to invalidate previously issued tokens.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Mitigate JWT Revocation Challenges
&lt;/h2&gt;

&lt;p&gt;Although JWTs are stateless, there are strategies to handle revocation effectively:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Token Expiration: Issue short-lived tokens that expire quickly, minimizing the impact of a compromised or outdated token.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Refresh Tokens: Use a separate, long-lived refresh token to issue new access tokens while maintaining control over session longevity.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Blacklist Tokens: Maintain a server-side blacklist of invalidated tokens, though this adds some statefulness to the system.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Versioned Claims: Include a version or timestamp in the token’s payload, and track the latest valid version server-side. If the version changes, previously issued tokens are invalidated.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You can learn more about an example of such an architecture here:&lt;br&gt;
&lt;a href="https://medium.com/@sergey.dudik/nginx-and-keycloak-a-perfect-pair-for-gateway-security-41a801e741f9" rel="noopener noreferrer"&gt;https://medium.com/@sergey.dudik/nginx-and-keycloak-a-perfect-pair-for-gateway-security-41a801e741f9&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The choice between sessions and JWTs often depends on your application’s specific requirements:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Choose sessions for applications needing immediate token revocation, tight server-side control, or enhanced security.&lt;/li&gt;
&lt;li&gt;Opt for JWTs if your priority is scalability, simplicity, and compatibility with distributed systems or APIs.&lt;/li&gt;
&lt;li&gt;Both technologies have their strengths and trade-offs, and understanding these will help you implement an authentication system that aligns with your security, scalability, and architectural goals.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Thanks for your reading!
&lt;/h2&gt;

&lt;p&gt;I’d love to hear your thoughts, so please feel free to leave a comment, give a clap, or follow me. 👏&lt;/p&gt;

&lt;p&gt;If you enjoyed this, consider sharing it with your community, tech friends, and anyone else you think might be interested. Also, don’t forget to follow me on &lt;a href="https://www.linkedin.com/in/sergey-dudik/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; for more updates!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Angular 18 New Features</title>
      <dc:creator>Sergey Dudik</dc:creator>
      <pubDate>Sun, 05 May 2024 07:21:03 +0000</pubDate>
      <link>https://dev.to/sergey-dudik/angular-18-new-features-3pip</link>
      <guid>https://dev.to/sergey-dudik/angular-18-new-features-3pip</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9511n02plgs8vaw2v022.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9511n02plgs8vaw2v022.png" alt="Angular"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Angular, one of the leading frameworks for building web applications, has been consistently evolving to meet the demands of modern web development. With each iteration, it brings forth new features, optimisations, and improvements. As the community eagerly awaits the release of Angular 18, here’s a look at what we might expect from this next major version.&lt;/p&gt;

&lt;p&gt;Angular 18 is set to be released in May 2024, and there are already several features confirmed for inclusion in the upcoming version that we can discuss.&lt;/p&gt;

&lt;h2&gt;
  
  
  Route Redirects with Functions
&lt;/h2&gt;

&lt;p&gt;Angular 18 introduces a new feature for managing redirects. Now, instead of using strings, we can employ functions to specify the redirect URL within the redirectTo property of the Route object. This enhancement offers increased flexibility in routing and opens up new possibilities.&lt;/p&gt;

&lt;p&gt;Within the function, the framework grants access to an object containing information about the URL.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// 
export const routes: Routes = [
  {
    path: 'page1',
    redirectTo: '/page2',
    pathMatch: 'full'
  }
]; 


//redirectTo function
export const routes: Routes = [
  {
    path: 'page1',
    redirectTo: (url) =&amp;gt; { 
      return '/page2'; 
    },
    pathMatch: 'full'
  }
];


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The function must return a string or a UrlTree. In Angular, a UrlTree is a data structure representing a URL. It’s essentially a parsed representation of a URL that Angular’s router uses to navigate within an application. The UrlTree encapsulates information such as the URL’s segments, query parameters, and fragments. It’s commonly used in Angular’s routing system for tasks like URL manipulation, navigation, and routing guards. By using UrlTree, Angular ensures consistent and reliable navigation behaviour within applications.&lt;/p&gt;

&lt;p&gt;The “url” object contains all information about the route, including its data, title, query parameters, routing segment, and more.&lt;/p&gt;

&lt;h2&gt;
  
  
  New RedirectCommand
&lt;/h2&gt;

&lt;p&gt;Angular version 18 introduces the new RedirectCommand class, designed to handle NavigationExtras. This addition allows for enhanced redirection capabilities within Guards and Resolvers. The integration of the RedirectCommand class greatly improves maintainability and flexibility, making it easier to manage complex navigation patterns in Angular applications.&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;const route: Route = {&lt;br&gt;
  path: 'page1',&lt;br&gt;
  component: PageComponent,&lt;br&gt;
  canActivate: [&lt;br&gt;
    () =&amp;gt; {&lt;br&gt;
      const router: Router = inject(Router);&lt;br&gt;
      const urlTree: UrlTree = router.parseUrl('./page2');&lt;br&gt;
      return new RedirectCommand(urlTree, { skipLocationChange: true });&lt;br&gt;
    },&lt;br&gt;
  ],&lt;br&gt;
};&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  ng-content default content&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;Now it’s allowed to put the default content into the ng-content tag. This feature is a logical extension of the ng-content element. If there’s a tag for content, it follows that default content should be included within the tag itself.&lt;/p&gt;

&lt;p&gt;For instance, if you have a component with ng-content in its template, you can also include default content that will be rendered if no content is provided for it.&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;&amp;lt;div&amp;gt;&lt;br&gt;
   &amp;lt;h1&amp;gt;Header&amp;lt;/h1&amp;gt;&lt;br&gt;
   &amp;lt;ng-content&amp;gt;Default&amp;lt;/ng-content&amp;gt;&lt;br&gt;
&amp;lt;/div&amp;gt;&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Zoneless applications&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;One of the primary objectives of Signals is to enable applications to operate without zone.js. Initially, this would have been achievable solely through Signal Components. However, the landscape has since evolved. Now, it will be possible to achieve this without using Signal Components, starting with Angular 18, which is set to release next month.&lt;/p&gt;

&lt;p&gt;Matthieu Riegler and Enea Jahollari have each published articles concentrating on this subject.&lt;/p&gt;

&lt;p&gt;Matthieu’s article explores the new hybrid change detection system, where any Signal change, an async pipe, or any other operation that invokes markForCheck will now automatically trigger Change Detection, even if the operation occurs outside of zone.js (an edge case).&lt;/p&gt;

&lt;p&gt;Enea’s article discusses the process of disabling zone.js entirely and depending solely on these new trigger mechanisms for managing application state changes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://justangular.com/blog/a-new-era-for-angular-zoneless-change-detection" rel="noopener noreferrer"&gt;https://justangular.com/blog/a-new-era-for-angular-zoneless-change-detection&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Thanks for your reading!
&lt;/h2&gt;

&lt;p&gt;I’d love to hear your thoughts, so please feel free to leave a comment, give a clap, or follow me. 👏&lt;/p&gt;

&lt;p&gt;If you enjoyed this, consider sharing it with your community, tech friends, and anyone else you think might be interested. Also, don’t forget to follow me on &lt;a href="https://www.linkedin.com/in/sergey-dudik/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; for more updates!&lt;/p&gt;

</description>
      <category>angular</category>
      <category>javascript</category>
      <category>typescript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Automating Workflows: Harnessing GitHub Actions, Docker, and GitHub npm Package</title>
      <dc:creator>Sergey Dudik</dc:creator>
      <pubDate>Wed, 24 Apr 2024 12:12:22 +0000</pubDate>
      <link>https://dev.to/sergey-dudik/automating-workflows-harnessing-github-actions-docker-and-github-npm-package-4m9h</link>
      <guid>https://dev.to/sergey-dudik/automating-workflows-harnessing-github-actions-docker-and-github-npm-package-4m9h</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr53hz2xhm0t2qbn7ypsm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr53hz2xhm0t2qbn7ypsm.png" alt="Github docker CI/CD"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the ever-evolving landscape of software development, streamlining workflows is paramount to success. In this article, we’ll explore how to leverage the powerful combination of GitHub Actions, Docker, and the GitHub npm Package to automate and optimize your development processes. From automating CI/CD pipelines to seamlessly managing dependencies, join us as we delve into the world of automation and discover how these tools can revolutionize your development workflow.&lt;/p&gt;

&lt;h2&gt;
  
  
  Github, NPM registry, Docker
&lt;/h2&gt;

&lt;p&gt;In today’s software development landscape, GitHub stands out as the most popular platform for storing and managing Git repositories. Beyond its fundamental role in version control, GitHub offers additional functionalities, including the capability to host private NPM registry. This feature facilitates the storage and sharing of JavaScript and TypeScript code among projects and teams, enhancing collaboration and code reusability across your organization.&lt;/p&gt;

&lt;p&gt;GitHub Actions allows you to automate tasks for your projects, such as checking code styles, running tests, building Docker images, deploying to different environments, and more.&lt;/p&gt;

&lt;p&gt;When discussing Docker, it’s common practice to build your application, library, or any code within a specific Docker image. Within this image, you can define the version of the Node machine, as well as any external resources and libraries required during the build process. This approach offers remarkable convenience, as it eliminates the need to rely on a specific PC or virtual machine with all the necessary setup. Instead, you can prepare the environment at the Docker level once and reuse it consistently across different machines and environments, ensuring consistency and reproducibility throughout your development workflow.&lt;/p&gt;

&lt;p&gt;However, a challenge arises when you attempt to build your application within Docker and it requires an npm library stored in your GitHub NPM private registry. Moreover, this process should be feasible within GitHub Actions. In this article, I will guide you through the setup process for achieving this seamlessly!&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Utilize a Private GitHub Registry?
&lt;/h2&gt;

&lt;p&gt;Firstly, let’s begin with a simple scenario involving routing. Picture a project with a dependency from a private NPM registry.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

{
  ...
  "dependencies": {
    ...
    "@targsoft/private-lib": "^1.0.0",
    ...
  }
  ...
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;First of all, you need to generate a new GitHub Token. You can generate a token in your GitHub account settings at &lt;a href="https://github.com/settings/tokens" rel="noopener noreferrer"&gt;https://github.com/settings/tokens&lt;/a&gt;. Make sure to add the ‘read:packages’ scope to your token.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F36x15nd784de1jv6ute5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F36x15nd784de1jv6ute5.png" alt="Github Personal Token"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you’ve obtained your token, you have two options:&lt;/p&gt;

&lt;p&gt;Add your token to your global npm configuration. Open your terminal and run the following commands:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

npm login --registry=https://npm.pkg.github.com --scope=@targsoft
login: your username password=TOKEN


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;where scope is your registry name&lt;/p&gt;

&lt;p&gt;Alternatively, you can create an .npmrc file next to your package.json file with the following content:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

@targsoft:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=TOKEN
always-auth=true


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This should do the trick, and your global npm will fetch the library from the private registry. Try running ‘npm install’ to see if it works!&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use a Private GitHub Registry inside Docker?
&lt;/h2&gt;

&lt;p&gt;Okay, so it’s pretty clear how to use the GitHub registry from your local machine. But what if you have a Dockerfile that builds your application within itself and then runs the application? For example, it could be a small web application with nginx as the web server.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

FROM node:20-alpine AS build


WORKDIR /opt
COPY ./package.json ./yarn.lock /opt/

RUN --mount=type=secret,id=npmrc,target=/root/.npmrc yarn install --frozen-lockfile

COPY . .

RUN yarn audit --omit=dev
RUN yarn build


FROM nginx:1.25.4-alpine AS runtime
COPY --from=build /opt/dist/targpatrol-main-frontend /usr/share/nginx/html
COPY docker/nginx.conf /etc/nginx/nginx.conf
CMD ["/bin/sh",  "-c",  "envsubst &amp;lt; /usr/share/nginx/html/assets/env.template.js &amp;gt; /usr/share/nginx/html/assets/env.js &amp;amp;&amp;amp; exec nginx -g 'daemon off;'"]


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The trick here is to pass secrets into your Dockerfile so that npm inside Docker can access the GitHub private registry.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

RUN --mount=type=secret,id=npmrc,target=/root/.npmrc yarn install --frozen-lockfile


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As you can see, we mount secrets before installing packages. This ensures that npm has the necessary credentials to fetch dependencies from the private registry.&lt;/p&gt;

&lt;p&gt;The Docker Compose file will resemble the following:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

version: '3.9'

secrets:
  npmrc:
    file: ./.npmrc

....

services:
  targpatrol-main-frontend:
    build:
      context: ../../targpatrol-main-frontend
      secrets:
        - npmrc
    container_name: targpatrol-main-frontend
    restart: always
    networks:
      - targpatrol-docker-network


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;.npmrc is the same file we used to fetch library using global npm.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

@targsoft:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=TOKEN
always-auth=true


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now you can run try to build the container:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

docker compose up --build --force-recreate


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  How to use Github Action to build Docker image?
&lt;/h2&gt;

&lt;p&gt;Okay, now that we’re able to build the Docker image on our local machines, what if we want to use GitHub Actions to build the image? Here’s how we need to do it.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

name:  targpatrol-main-frontend-pr-opened

...

jobs:
  build-and-test:
    runs-on: ubuntu-latest
    defaults:
      run:
        shell: bash
        working-directory: ${{ env.SERVICE }}

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Setup node
        uses: actions/setup-node@v3
        with:
          node-version: '20.x'
          registry-url: 'https://npm.pkg.github.com'
          scope: '@targsoft'

      - name: Install npm packages
        run: yarn install --frozen-lockfile
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Lint
        run: yarn lint

      - name: Audit
        run: yarn audit --omit=dev

      - name: Build
        run: yarn build

      - name: Docker Build and push to AWS ECR
        uses: docker/build-push-action@v5
        with:
          context: ${{ env.SERVICE }}
          file: ${{ env.SERVICE }}/Dockerfile
          secrets: |
            "npmrc=${{ secrets.NPMRC_SECRET_FILE }}"
          push: false


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This is an example of how to set up Node.js inside a GitHub action. The NPM_TOKEN should be set up at the repository or organization level. NPMRC_SECRET_FILE is the GitHub Action secret that contains the same content as the .npmrc file.&lt;/p&gt;

&lt;h2&gt;
  
  
  Don’t forget about Dependabot
&lt;/h2&gt;

&lt;p&gt;If you are using Dependabot to watch your packages versions you have to create separate secrets for it because it won’t take secrets from your Github Actions.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faw00iuae2q6wi9r2e95y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faw00iuae2q6wi9r2e95y.png" alt="Dependabot token"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In conclusion, the integration of GitHub Actions, Docker, and the GitHub npm Package presents a powerful solution for automating workflows in software development. By harnessing these tools, developers can streamline their processes, increase productivity, and ensure consistency across projects and teams. From automating builds and deployments to managing dependencies seamlessly, the possibilities are endless. As technology continues to evolve, mastering these tools will become increasingly essential for staying competitive in the ever-changing landscape of software development. So, dive in, experiment, and discover the endless possibilities of automating your workflows with GitHub Actions, Docker, and the GitHub npm Package.&lt;/p&gt;

</description>
      <category>devops</category>
      <category>github</category>
      <category>docker</category>
      <category>npm</category>
    </item>
    <item>
      <title>Nginx and Keycloak: A Perfect Pair for Gateway Security</title>
      <dc:creator>Sergey Dudik</dc:creator>
      <pubDate>Fri, 05 Jan 2024 07:38:04 +0000</pubDate>
      <link>https://dev.to/sergey-dudik/nginx-and-keycloak-a-perfect-pair-for-gateway-security-3ief</link>
      <guid>https://dev.to/sergey-dudik/nginx-and-keycloak-a-perfect-pair-for-gateway-security-3ief</guid>
      <description>&lt;p&gt;In today’s fast-paced digital landscape, ensuring robust security at every point of user interaction is paramount. While there are numerous tools available to fortify our applications, finding the perfect synergy between them can be a challenge. Enter the dynamic duo: Nginx and Keycloak. When paired together, these powerful technologies provide an unparalleled security solution for your gateway. Nginx, known for its high-performance and scalability, combined with the robust authentication and authorization mechanisms of Keycloak, creates a fortress, safeguarding your applications from unauthorized access. In this article, we’ll explore the ins and outs of this compelling combination, demonstrating how you can harness their collective strengths to build a fortified, yet user-friendly, gateway for your applications.&lt;/p&gt;

&lt;p&gt;Before diving into Nginx and Keycloak, let’s revisit some foundational concepts of security.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding the Difference: Authentication vs. Authorization
&lt;/h2&gt;

&lt;p&gt;In the realm of security, the terms “authentication” and “authorization” often come up. Although they might sound similar and are sometimes used interchangeably, they have distinct meanings and functions. Let’s delve into each of these terms to understand their differences and importance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Authentication&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Definition: Authentication refers to the process of verifying the identity of a user, system, or application. It answers the question, “Are you who you say you are?”&lt;/p&gt;

&lt;p&gt;How it Works: The most common form of authentication is a username and password combination. When a user enters these credentials, the system compares them against stored data to verify their identity. Other methods include biometrics (like fingerprint or facial recognition), OTPs (one-time passwords), and hardware tokens.&lt;/p&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Entering a password to log into your email account.&lt;/li&gt;
&lt;li&gt;Using a fingerprint to unlock your smartphone.&lt;/li&gt;
&lt;li&gt;Receiving an SMS code to confirm your identity on a banking website.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Authorization&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Definition: Once authentication is established, authorization determines what that user, system, or application is permitted to do. It answers the question, “Do you have permission to perform this action?”&lt;/p&gt;

&lt;p&gt;How it Works: Authorization is typically managed by setting permissions or roles. For instance, a user might be granted read-only access to a database, while an admin has the rights to both read and modify it.&lt;/p&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;p&gt;A standard employee might access a company portal but can’t make changes to certain critical documents. An administrator, on the other hand, can modify, delete, or even share those documents.&lt;/p&gt;

&lt;p&gt;In a file-sharing app, you might grant some users the ability to view a file, while others can edit it.&lt;/p&gt;

&lt;p&gt;While both authentication and authorization play critical roles in security, they serve distinct purposes:&lt;/p&gt;

&lt;p&gt;Authentication ensures you are communicating with the right entity by validating their identity.&lt;/p&gt;

&lt;p&gt;Authorization ensures that entity has the correct permissions to perform certain actions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Gateway?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Also known as API Gateway is a service that acts as an intermediary for requests from clients seeking resources from other servers or services. Many organizations use API Gateways in microservice architectures to manage and secure the complex interactions between microservices. Popular API Gateways include Amazon API Gateway, Kong, Apigee, and WSO2.&lt;/p&gt;

&lt;p&gt;There is a great article if you want to know more about API Gateway and its usage:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://medium.com/buildpiper/how-do-api-gateways-work-3b989fdcd751"&gt;https://medium.com/buildpiper/how-do-api-gateways-work-3b989fdcd751&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How can you secure your backend?&lt;br&gt;
Imagine we are developing a web application comprised of three components:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Single-page application (SPA) built with frameworks like React or Angular&lt;/li&gt;
&lt;li&gt;Data Service that handles all CRUD operations related to our domain entities and manages the connection to the database&lt;/li&gt;
&lt;li&gt;Report Service that fetches data from the Data Service and encapsulates the logic for generating custom reports&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy7czjvewdk7u3htgvtq9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy7czjvewdk7u3htgvtq9.png" alt="Typical architecture" width="720" height="301"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When it comes to securing the backend, there are three primary strategies to consider:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Each microservice handles its own authentication and authorization.&lt;/li&gt;
&lt;li&gt;The gateway manages authentication while individual services are responsible for authorization.&lt;/li&gt;
&lt;li&gt;The gateway takes care of both authentication and authorization.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each approach has its unique strengths and limitations. For the sake of brevity, this article won’t delve into which strategy is superior. Truthfully, determining the best fit requires a comprehensive understanding of the system in question.&lt;/p&gt;

&lt;p&gt;In the following sections, we will explore the second and third strategies in-depth, focusing on how NGINX and Keycloak can be effectively employed for these purposes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Keycloak?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Keycloak is an open-source Identity and Access Management (IAM) tool developed by Red Hat. It provides advanced features such as Single Sign-On (SSO), Identity Brokering, and Social Login without the need for deep, specialized security expertise.&lt;/p&gt;

&lt;p&gt;Keycloak’s blend of flexibility, comprehensive features, and active community support has solidified its reputation in the identity and access management space. As organizations continue to seek efficient ways to manage identities without compromising security, tools like Keycloak remain indispensable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Nginx?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Nginx was created by Igor Sysoev in 2002, with its first public release in 2004. Originally developed to address the C10K problem (handling 10,000 simultaneous connections), Nginx was built from the ground up to be highly efficient and scalable.&lt;/p&gt;

&lt;p&gt;At its core, Nginx is a web server. But over the years, it has evolved into so much more. Today, Nginx can also function as a reverse proxy server, load balancer, mail proxy server, and even an HTTP cache.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nginx Plus issue&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Nginx offers a free version of its software, but there’s also a premium paid version known as Nginx Plus. While Nginx Plus supports Single Sign-On with Keycloak, the free version unfortunately does not. It’s a bit disappointing, given the popularity of both Nginx and Keycloak. At &lt;a href="https://targpatrol.com"&gt;TargPatrol&lt;/a&gt;, we utilize both tools, so we’ve had to devise a method for them to effectively communicate with each other.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Modernized architecture&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s make some adjustments to our architecture. The updated version is depicted in the image below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F931fe3g9ofcxp5o357lm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F931fe3g9ofcxp5o357lm.png" alt="Modernized architecture" width="720" height="309"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As illustrated, the Nginx service now functions as an API Gateway. Its primary role is to handle both authentication and authorization. Meanwhile, the Keycloak service acts as our Single Sign-On (SSO) server. The Data Service and Report Service process requests coming from Nginx, but they no longer manage authentication or authorization for these requests.&lt;/p&gt;

&lt;p&gt;I won’t delve into the integration of SPA with Keycloak in this article, as there are numerous comprehensive resources available on this topic. For instance, you can refer to this well-written guide: &lt;a href="https://medium.hexadefence.com/securing-a-react-app-using-keycloak-ac0ee5dd4bfc"&gt;https://medium.hexadefence.com/securing-a-react-app-using-keycloak-ac0ee5dd4bfc&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;How should we handle authentication in this scenario? We can use nginx authentication proxy.&lt;/p&gt;

&lt;p&gt;Now, let’s examine the nginx configuration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http {

  ...

  location /auth {
     proxy_ssl_server_name on;
     proxy_pass  https://targpatrol-keycloak.local/realms/targpatrol-dev/protocol/openid-connect/userinfo;
     proxy_pass_request_body off;
     proxy_set_header Content-Length "";
     proxy_set_header X-Original-URI $request_uri;
  }

  location /data {
     auth_request /auth;
     auth_request_set $auth_status $upstream_status;
     error_page 401 = @handle_unauthorized;

     proxy_pass http://data-service.local;
     include /etc/nginx/common/ssl-headers.conf;

     js_content authService.authorize;
  }

  location /report {
     auth_request /auth;
     auth_request_set $auth_status $upstream_status;
     error_page 401 = @handle_unauthorized;

     proxy_pass http://report-service.local;
     include /etc/nginx/common/ssl-headers.conf;

     js_content authService.authorize;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What’s happening here? First, we’ve defined the /auth route that validates our request using Keycloak. We simply send the request with headers only to Keycloak, requesting user information. If we possess a valid token in our header, Keycloak will respond with a 200 OK, returning the current user’s data.&lt;/p&gt;

&lt;p&gt;The routes for the Data and Report services contain the ‘auth_request’ instruction. Every time we attempt to access them, a request will be sent to Keycloak first.&lt;/p&gt;

&lt;p&gt;Alright, we understand the authentication process, but what about authorization? For this, we can leverage a functionality in nginx called ngx_http_js_module. This module permits the execution of JavaScript code on a request. Let’s delve into the ‘js_content’:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function extractPayload (token) {
   const tokenParts = token.split('.');
   const encodedPayload = tokenParts[1];
   const decodedPayload = Buffer.from(encodedPayload, 'base64').toString('utf-8');

   return JSON.parse(decodedPayload);
}


function authorize(request) {
   const token = request.headersIn.Authorization;

   if (!token || !(token.slice(0, 7) === 'Bearer ')) {
       return false;
   }

   const payload = extractPayload(token);
   const roles = payload['roles'];

   # request url
   const url = request.uri;


   # here we can compare url and roles
   # to allow or deny access  

   return false;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This file is named authService.js. It should contain a function named authorize since, in our js_content instruction, we reference it as authService.authorize (following the format fileName.functionName). Plain JavaScript can be utilized here. Initially, we parse the Authorization header to extract the Bearer token, which was generated by Keycloak, into an object form. Subsequently, we can match the roles with the request URL to either grant or deny the request. It’s all quite straightforward!&lt;/p&gt;

&lt;p&gt;One challenge with this approach is that every request is directed to Keycloak. A possible solution is to transition from nginx’s js_content to a Node.js service (or another suitable language). This service would have server-side integration with Keycloak. It’s worth noting that only Nginx Plus supports this, not the free version. For more details, you can refer to: Keycloak’s documentation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In summary, the synergy between Nginx and Keycloak offers a compelling solution for gateway security. While Nginx efficiently manages and routes web traffic, Keycloak ensures robust authentication and authorization. Their combined capabilities create a fortified layer of defense, enhancing both user experience and system security. By seamlessly integrating these tools, businesses can achieve not only heightened protection but also streamlined operations. As the digital landscape continues to evolve, tools like Nginx and Keycloak are proving indispensable for those seeking a balanced combination of performance, flexibility, and security.&lt;/p&gt;

&lt;p&gt;Source: &lt;a href="https://medium.com/p/41a801e741f9"&gt;https://medium.com/p/41a801e741f9&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Mastering AWS CDK: Setting Up a Custom Domain for Your HTTP Gateway</title>
      <dc:creator>Sergey Dudik</dc:creator>
      <pubDate>Mon, 18 Dec 2023 12:46:03 +0000</pubDate>
      <link>https://dev.to/sergey-dudik/mastering-aws-cdk-setting-up-a-custom-domain-for-your-http-gateway-6cb</link>
      <guid>https://dev.to/sergey-dudik/mastering-aws-cdk-setting-up-a-custom-domain-for-your-http-gateway-6cb</guid>
      <description>&lt;p&gt;In the ever-evolving landscape of cloud services, the ability to customize and tailor configurations is more than just a luxury — it’s a necessity. For developers and businesses keen on leveraging the AWS ecosystem, the Cloud Development Kit (CDK) has emerged as an invaluable tool. Not only does it simplify infrastructure management, but it also provides a programmatic way to deploy resources on AWS. One such resource that often requires a touch of personalization is the HTTP gateway. Having a custom domain for this gateway not only enhances your brand’s visibility but also instills trust in your users.&lt;/p&gt;

&lt;p&gt;In this article, we’ll embark on a step-by-step journey, unraveling the mysteries of setting up a custom domain name for your HTTP gateway using the AWS CDK. Whether you’re a seasoned AWS veteran or a newcomer eager to dive deep, this guide promises to offer insights and actionable steps to elevate your cloud game.&lt;/p&gt;

&lt;p&gt;So, grab your favorite cup of coffee, put on your developer hat, and let’s dive right in!&lt;/p&gt;

&lt;h2&gt;
  
  
  Typical AWS infrastructure
&lt;/h2&gt;

&lt;p&gt;Let’s examine the basic infrastructure that is commonly used these days. While working on &lt;a href="https://targpatrol.com"&gt;TARGPatrol&lt;/a&gt;, we adopted a similar approach as it allows for the creation of flexible and powerful solutions.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7xsnk0o4b54elm60gzlz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7xsnk0o4b54elm60gzlz.png" alt="AWS Infrastructure" width="789" height="501"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;AWS VPC allows you to group all your infrastructure into an isolated virtual network. This virtual network mirrors a conventional network you’d manage in your own data center, while leveraging the scalable infrastructure of AWS.&lt;/li&gt;
&lt;li&gt;AWS API Gateway is a fully managed service, streamlines the process for developers to craft, release, sustain, oversee, and safeguard APIs regardless of their size. Serving as the “entry point” for apps to retrieve data or tap into business logic from backend services, this tool allows for the creation of both RESTful and WebSocket APIs, facilitating instantaneous bidirectional communication. Moreover, API Gateway is compatible with containerized, serverless, and traditional web-based workloads. Two types of gateways exist. Create RESTful APIs tailored for serverless tasks and HTTP backends using HTTP APIs. For APIs that solely need proxy functionality, HTTP APIs are the top pick. However, if you need both proxy functionality and comprehensive API management within one package, API Gateway provides REST APIs as an option.&lt;/li&gt;
&lt;li&gt;AWS Route 53 is a robust and scalable Domain Name System (DNS) web service. It directs user requests to web applications hosted either on AWS or on-premises setups. Additionally, AWS Route 53 enables the registration and linkage of custom domains to your AWS API Gateway.&lt;/li&gt;
&lt;li&gt;AWS Lambda is a serverless compute service, driven by events, which facilitates the execution of code for almost any application or backend process without the need to handle server management. Lambda can be activated by more than 200 AWS services and SaaS applications, ensuring you only pay for your actual usage.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Using AWS Lambda isn’t obligatory. Alternatives include services like EC2, ECS, or EKS.&lt;/p&gt;

&lt;p&gt;In the sprawling universe of cloud services, infrastructure as code (IAC) has carved out a significant niche. The AWS Cloud Development Kit (CDK), Amazon’s proprietary foray into this space, represents a paradigm shift in how we think about cloud resource provisioning.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is AWS CDK?
&lt;/h2&gt;

&lt;p&gt;The AWS CDK is an open-source software development framework to define cloud infrastructure in code and provision it through AWS CloudFormation. Unlike traditional CloudFormation where developers write cumbersome YAML or JSON templates, with CDK, they can leverage the power of modern programming languages such as TypeScript, Python, Java, or C#. This allows for more abstraction, reusability, and a more intuitive development experience.&lt;/p&gt;

&lt;p&gt;Key Benefits of AWS CDK:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Intuitive Infrastructure Design: Developers can use their preferred programming languages, making the process more fluid and reducing the learning curve.&lt;/li&gt;
&lt;li&gt;Reusable Components: CDK introduces the concept of constructs — pre-built pieces of cloud infrastructure. This means less repetitive code and more focus on the unique aspects of a given project.&lt;/li&gt;
&lt;li&gt;Stronger Validation: By leveraging the capabilities of mainstream programming languages, CDK provides early feedback through IDEs, making it easier to catch issues before they reach the deployment stage.&lt;/li&gt;
&lt;li&gt;Seamless Integration with AWS Services: Given its native nature, CDK smoothly integrates with the vast AWS ecosystem, making it a breeze to incorporate various AWS services into your infrastructure.&lt;/li&gt;
&lt;li&gt;Built-in Best Practices: AWS CDK has built-in defaults that adhere to AWS best practices, ensuring optimal configurations and security.&lt;/li&gt;
&lt;li&gt;Flexibility: While CDK offers high-level components for quick setup, developers also have the option to dive deep and customize low-level resources if needed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The entire TARGParol infrastructure was constructed using AWS CDK/TypeScript, and our team has experienced no problems with it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Preparation
&lt;/h2&gt;

&lt;p&gt;You’ll need to begin by selecting and registering a custom domain. While this can be done through various providers such as GoDaddy, Cloudflare, etc., and subsequently transferring DNS control to AWS, I’ll demonstrate how to accomplish this directly within AWS.&lt;/p&gt;

&lt;p&gt;Navigate to Route 53 Service and click to Domains -&amp;gt; Registered domains.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ysjkbf8hrr6f7p7afwb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ysjkbf8hrr6f7p7afwb.png" alt="AWS Domain registration" width="800" height="470"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next, you’ll need to choose an appropriate name for your custom domain and purchase it if it’s available. It will take a few minutes for the process to complete, after which you can view your domain in the Hosted Zones.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqzxrvfy0xpo6ev0y0fvk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqzxrvfy0xpo6ev0y0fvk.png" alt="AWS Hosted zones" width="800" height="295"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Order certificates
&lt;/h2&gt;

&lt;p&gt;Once you’ve completed the domain registration, the next step is to obtain a certificate to secure your traffic using the HTTPS protocol. While AWS CDK can facilitate the certificate ordering, it’s a relatively static process that can be handled separately. Head to the AWS Certificate Manager and select “Request.” Opt for a public certificate. When prompted for a domain name, enter the one you purchased earlier. If you’re looking to secure a subdomain, you can specify additional names, such as sub.example.com. Alternatively, you can utilize wildcards like *.example.com to safeguard all subdomains under the primary domain. Opt for DNS Validation to confirm the link between your certificate and domain. You can rely on AWS during this process: when prompted to add validation DNS records, simply click “Ok.”&lt;/p&gt;

&lt;p&gt;It may take a few minutes to generate the certificate. Once completed, you can view your certificate in the AWS Certificate Manager dashboard.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmez7qnfhwignmjhkzo5w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmez7qnfhwignmjhkzo5w.png" alt="AWS Certificate manager" width="800" height="354"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To integrate it into your AWS CDK code, you’ll need its Arn. Simply click on the certificate and copy the Arn value.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftcmo2yhgshjptu61o9op.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftcmo2yhgshjptu61o9op.png" alt="AWS Certificate Arn" width="800" height="305"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Let’s put our hands on the code
&lt;/h2&gt;

&lt;p&gt;I hope you’re familiar with the AWS CDK. If not, there’s a fantastic article you can follow to take your first steps (&lt;a href="https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html"&gt;https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html&lt;/a&gt;). In short, you just need to install the AWS CDK CLI and create a new project.&lt;/p&gt;

&lt;p&gt;The very first thing you need to define in an AWS CDK stack is your VPC. You can create it with just a few lines of code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    const vpc = new Vpc(this, "VPC", {
      vpcName: "VpcName",
      ipAddresses: IpAddresses.cidr("10.0.0.0/16"),
      subnetConfiguration: [
        { name: 'Public', cidrMask: 24, subnetType: SubnetType.PUBLIC },
        {
          name: 'Private',
          cidrMask: 24,
          subnetType: SubnetType.PRIVATE_WITH_EGRESS,
        },
        {
          name: 'Isolated',
          cidrMask: 24,
          subnetType: SubnetType.PRIVATE_ISOLATED,
        },
      ],
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we’re establishing a new VPC with three subnets. While this isn’t directly related to the topic of custom domains, it’s prudent to prepare for any additional resources you might want to introduce in the future. Note that natGateways aren’t crucial if we’re using Lambda as the backend. However, if you plan to deploy EC2 or ECS/EKS instances and need to provide them with Internet access, at least one natGateway is essential.&lt;/p&gt;

&lt;p&gt;We require several constants from the resources that were manually created:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const domainName = "targpatrol.xyz";
const hostedZoneId = "Z01395012LPLFQI32IEEA";
const certArn ="arn:aws:acm:us-east-1:988135634994:certificate/496295d2-317a-4622-85a2-4cc5b6ea6519";
const lambdaRepository = "111122223333.dkr.ecr.us-east-1.amazonaws.com";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you’re uncertain about locating these values, refer to the screenshot provided earlier.&lt;/p&gt;

&lt;p&gt;Now you can import the ‘HostedZone’ and establish a new domain. Additionally, we need to set up a DNS record that will direct traffic to the API gateway, which we’ll set up in a later step.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const hostedZoned = HostedZone.fromHostedZoneAttributes(
 this,
 "HostedZone",
 {
   zoneName: props.domainName,
   hostedZoneId: props.hostedZoneId,
 }
);


const domainName = new DomainName(this, "DomainName", {
 domainName: props.domainName,
 certificate: Certificate.fromCertificateArn(
   this,
   "Certificate",
   props.certArn
 ),
 securityPolicy: SecurityPolicy.TLS_1_2,
});


new ARecord(this, "DnsRecord", {
 zone: hostedZoned,
 recordName: props.domainName,
 target: RecordTarget.fromAlias(
   new ApiGatewayv2DomainProperties(
     domainName.regionalDomainName,
     domainName.regionalHostedZoneId
   )
 ),
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the domain and DNS set up, we can now proceed to the HTTP API Gateway. But first, let’s craft a simple Lambda function to manage our requests. While there are several methods to create a Lambda, I’ll utilize the AWS sample Lambda function for this demonstration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const lambda = new DockerImageFunction(this, "LambdaFunction", {
 functionName: "FunctionName",
 code: DockerImageCode.fromEcr(
   Repository.fromRepositoryName(
     this,
     "LambdaRepository",
     props.lambdaRepository
   ),
   { tagOrDigest: "latest" }
 ),
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The final action involves setting up the HTTP API Gateway and directing the domain towards it. As touched upon earlier, AWS offers various API Gateway types, including HTTP API and REST API. To put it briefly, while the REST API offers more features, it comes at a price tag three times higher. The HTTP API can be likened to a basic nginx proxy service, facilitating control over your HTTP(S) traffic. For this tutorial, I’ll be focusing on the HTTP API Gateway.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const gateway = new HttpApi(this, "HttpApiGateway", {
 disableExecuteApiEndpoint: true,
 defaultDomainMapping: {
   domainName,
 },
});


gateway.addRoutes({
 path: "/api/v1/test",
 methods: [HttpMethod.POST],
 integration: new HttpLambdaIntegration("LambdaIntegration", lambda),
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Conclusion: The Power of AWS CDK&lt;br&gt;
Navigating the AWS ecosystem can initially seem daunting, but tools like the AWS CDK are specifically designed to simplify and streamline the process. By allowing developers to use familiar programming languages and providing an intuitive framework to define and deploy cloud infrastructure, AWS CDK genuinely revolutionizes the cloud development experience.&lt;/p&gt;

&lt;p&gt;The examples provided in this article merely scratch the surface of what’s possible with AWS CDK. As you delve deeper and experiment more, you’ll uncover a myriad of opportunities to optimize, automate, and innovate.&lt;/p&gt;

&lt;p&gt;Embracing the AWS CDK means stepping into the future of cloud deployment, where flexibility meets efficiency. As always, continuous learning and adaptation are the keys to harnessing the full potential of any tool, AWS CDK being no exception.&lt;/p&gt;

&lt;p&gt;Thank you for joining us on this exploratory journey into the world of AWS CDK. We encourage you to dive in, experiment, and share your experiences with the broader developer community. Happy coding!&lt;/p&gt;

&lt;p&gt;P.S. All the code can be accessed in the repository linked here.&lt;/p&gt;

&lt;p&gt;Github:&lt;br&gt;
&lt;a href="https://github.com/sergey-dudik/aws-cdk-examples/tree/main/aws-route-53-custom-domain"&gt;https://github.com/sergey-dudik/aws-cdk-examples/tree/main/aws-route-53-custom-domain&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;On Medium: &lt;br&gt;
&lt;a href="https://medium.com/@sergey.dudik/mastering-aws-cdk-setting-up-a-custom-domain-for-your-http-gateway-9a6e61051201"&gt;https://medium.com/@sergey.dudik/mastering-aws-cdk-setting-up-a-custom-domain-for-your-http-gateway-9a6e61051201&lt;/a&gt;&lt;/p&gt;

</description>
      <category>aws</category>
      <category>devops</category>
      <category>development</category>
      <category>typescript</category>
    </item>
  </channel>
</rss>
