<?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 Idris Akintobi on Medium]]></title>
        <description><![CDATA[Stories by Idris Akintobi on Medium]]></description>
        <link>https://medium.com/@akintobiidris?source=rss-49ea7a7ba30b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xHK3qwUD6MvP_QhZ8FTcvQ.jpeg</url>
            <title>Stories by Idris Akintobi on Medium</title>
            <link>https://medium.com/@akintobiidris?source=rss-49ea7a7ba30b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 13:38:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akintobiidris/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[Understanding Go’s context Package: A Guide to Proper Usage]]></title>
            <link>https://medium.com/@akintobiidris/understanding-gos-context-package-a-guide-to-proper-usage-b568e200345c?source=rss-49ea7a7ba30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b568e200345c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Idris Akintobi]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 20:20:40 GMT</pubDate>
            <atom:updated>2025-11-13T20:20:40.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Understanding Go’s context package" src="https://cdn-images-1.medium.com/max/1001/1*RJL92hbS_eft_I6BqloQzA.png" /><figcaption>Understanding Go’s context package</figcaption></figure><p><em>A comprehensive guide to understanding and correctly implementing Go’s context package for robust concurrent applications</em></p><p>In the world of concurrent programming in Go, the context package stands as a fundamental tool for managing the lifecycle of goroutines, handling cancellations, and carrying request-scoped data. However, a misunderstanding of its proper application can lead to subtle bugs, resource leaks, and unexpected application behavior. This article will delve into the correct use of context in Golang, ensuring that you, as a Golang engineer, can leverage its power effectively and avoid common pitfalls.</p><h3>Why Context Matters</h3><p>At its core, the context package provides a mechanism to control and coordinate concurrent operations. Its primary purposes include:</p><h3>🚫 Cancellation</h3><p>It allows for the graceful termination of long-running operations when they are no longer needed, preventing unnecessary work and resource consumption.</p><h3>⏱️ Timeouts and Deadlines</h3><p>It enables setting time limits on operations, which is crucial for maintaining system responsiveness and preventing indefinite hangs.</p><h3>📦 Request-Scoped Data</h3><p>It provides a way to carry request-specific information, such as user IDs or trace IDs, through the layers of an application without cluttering function signatures with extra parameters.</p><p>A context.Context is an immutable interface that carries these signals and values across API boundaries. <strong>The convention in Go is to pass the context as the first argument to a function.</strong></p><h3>Understanding the Context Package</h3><p>The context package provides several functions to create and derive contexts:</p><h3>context.Background()</h3><p>Returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline. It is typically used at the highest level of an application (in main or init functions) as the starting point for all other contexts.</p><h3>context.TODO()</h3><p>Similar to Background(), this also returns an empty Context. It should be used as a placeholder when you are unsure which Context to use or when a function should accept a Context but hasn&#39;t been updated yet. It serves as a signal that the code needs to be revisited.</p><h3>context.WithCancel(parent Context)</h3><p>Returns a copy of the parent context along with a cancel function. Calling the cancel function signals that the work associated with this context should be stopped.</p><h3>context.WithDeadline(parent Context, d time.Time)</h3><p>Returns a copy of the parent context that will be canceled when the specified deadline is reached.</p><h3>context.WithTimeout(parent Context, timeout time.Duration)</h3><p>A convenience function that calls WithDeadline with a timeout relative to the current time.</p><h3>context.WithValue(parent Context, key, val interface{})</h3><p>Allows you to associate a key-value pair with a context. This should be used sparingly for request-scoped data, not for passing optional parameters.</p><h3>⚠️ Common Context Pitfalls</h3><p>Understanding the theory is one thing, but applying it correctly in real-world scenarios is what truly matters. Let’s explore some common situations where a misunderstanding of context can lead to problems.</p><h3>Scenario 1: The Database Operation Trap</h3><p>A frequent pattern in web services is to perform a database operation in response to an incoming HTTP request. The net/http package provides a Context() method on the *http.Request object, which is canceled when the client disconnects.</p><h3>❌ The Problem</h3><p>Consider an operation that needs to complete regardless of whether the client stays connected, such as processing a payment or creating a new user. If you pass the request’s context to this database operation, and the client disconnects, the context will be canceled. This cancellation will propagate to the database driver (if it supports contexts), potentially causing the database transaction to be rolled back.</p><h3>✅ The Solution</h3><p>For operations that should outlive the incoming request, you should <strong>not</strong> use the request’s context. Instead, create a new context, typically derived from context.Background().</p><p>Here’s a code example using SQLite to illustrate the wrong and right way:</p><h3>Incorrect Usage:</h3><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;database/sql&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;time&quot;<br><br> _ &quot;github.com/mattn/go-sqlite3&quot;<br>)<br><br>func setupDatabase() *sql.DB {<br> db, err := sql.Open(&quot;sqlite3&quot;, &quot;./test.db&quot;)<br> if err != nil {<br>  log.Fatal(err)<br> }<br> sqlStmt := `<br>    CREATE TABLE IF NOT EXISTS users (id INTEGER NOT NULL PRIMARY KEY, name TEXT, created_at DATETIME);<br>    `<br> _, err = db.Exec(sqlStmt)<br> if err != nil {<br>  log.Fatalf(&quot;%q: %s\n&quot;, err, sqlStmt)<br> }<br> return db<br>}<br><br>func handleRequest(w http.ResponseWriter, r *http.Request, db *sql.DB) {<br> reqCtx := r.Context()  // Initialize the request context<br> // ❌ Incorrectly passing the request context to a critical db operation.<br> // If the client disconnects, the context is cancelled, and the DB operation will fail.<br> err := criticalDBOperation(reqCtx, db)<br> if err != nil {<br>  log.Printf(&quot;Handler error: %v&quot;, err)<br>  http.Error(w, &quot;Database operation failed or was cancelled&quot;, http.StatusInternalServerError)<br>  return<br> }<br> fmt.Fprintln(w, &quot;Request processed and data saved.&quot;)<br>}<br><br>func criticalDBOperation(ctx context.Context, db *sql.DB) error {<br> // Simulate a delay. If a client disconnects during this time, the context is cancelled.<br> time.Sleep(5 * time.Second)<br> // db.ExecContext respects the context. If ctx.Done() is closed, it will return an error.<br> _, err := db.ExecContext(ctx, &quot;INSERT INTO users (name, created_at) VALUES (?, ?)&quot;, &quot;critical_user&quot;, time.Now())<br> if err != nil {<br>  log.Println(&quot;Database operation cancelled or failed:&quot;, err)<br>  return err<br> }<br> log.Println(&quot;Critical database operation completed successfully&quot;)<br> return nil<br>}<br><br>func main() {<br> db := setupDatabase()<br> defer db.Close()<br> http.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  handleRequest(w, r, db)<br> })<br> log.Println(&quot;Server starting on :8080&quot;)<br> log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))<br>}</pre><p>If you run this server, make a request with curl, and cancel curl before 5 seconds, you will see the &quot;Database operation cancelled or failed: context canceled&quot; message in the server logs.</p><h3>Correct Usage:</h3><pre>func handleRequest(w http.ResponseWriter, _ *http.Request, db *sql.DB) {<br> // Initialize db context. We can use timeout context here to prevent long running db operations but let keep it simple.<br> dbCtx := context.Background()<br> // ✅ Correctly create a new context for the DB operation that must complete.<br> // If the client disconnects, the DB operation will succeed.<br> // This operation should be run in a new goroutine so the HTTP handler can return immediately but let keep it as it is.<br> err := criticalDBOperation(dbCtx, db)<br> if err != nil {<br>  log.Printf(&quot;Handler error: %v&quot;, err)<br>  http.Error(w, &quot;Database operation failed or was cancelled&quot;, http.StatusInternalServerError)<br>  return<br> }<br> fmt.Fprintln(w, &quot;Request processed and data saved.&quot;)<br>}</pre><p>In this corrected version, the database operation runs with an independent context, ensuring it completes even if the client disconnects.</p><h3>Scenario 2: Background Task Independence</h3><p>Another common use case is spinning up a goroutine to perform a non-critical or “forgivable” task, like sending a login attempt email or logging analytics. It might seem convenient to pass the same context used by the main business logic to this background task.</p><h3>❌ The Problem</h3><p>If the context passed to the background goroutine is canceled for any reason (e.g., a timeout in the main logic), the background task will also be canceled. This might be undesirable.</p><h3>✅ The Solution</h3><p>For independent, non-critical background tasks, it’s often best to create a new, detached context. This ensures that the lifecycle of the background task is not tied to the lifecycle of the main operation.</p><h3>Incorrect Usage:</h3><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> // Simulating login authentication logic cancellable context<br> // We are using short-lived context here. This might happen due to client-side timeout, network issuesm server overload, or slow db queries.<br> ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)<br> defer cancel()<br><br> fmt.Println(&quot;Starting user authentication...&quot;)<br> // ❌ Start a background task with the same context<br> go sendLoginAttemptEmail(ctx)<br><br> // Wait to observe the goroutine&#39;s fate<br> time.Sleep(200 * time.Millisecond)<br>}<br><br>func sendLoginAttemptEmail(ctx context.Context) {<br> // Assuming context is needed for email sending logic<br> // In real usecase, we might as well want an internal timeout for the email itself, so it doesn&#39;t hang forever.<br> select {<br> case &lt;-time.After(100 * time.Millisecond):<br>  fmt.Println(&quot;Login attempt email sent successfully&quot;)<br> case &lt;-ctx.Done():<br>  fmt.Println(&quot;Failed to send login attempt email: context cancelled&quot;)<br> }<br>}</pre><h3>Correct Usage:</h3><pre>func main() {<br> // Simulating login authentication logic cancellable context<br> // We are using short-lived context here. This might happen due to client-side timeout, network issuesm server overload, or slow db queries.<br> _, cancel := context.WithTimeout(context.Background(), time.Millisecond)<br> defer cancel()<br><br> fmt.Println(&quot;Starting user authentication...&quot;)<br> // ✅ CORRECT: Start the background task with a new, independent context.<br> // Because the email sending is not dependent on the authentication&#39;s lifecycle.<br> go sendLoginAttemptEmail(context.Background())<br><br> // Wait to observe the goroutine&#39;s fate<br> time.Sleep(200 * time.Millisecond)<br>}</pre><p>Here, sendLoginAttemptEmail is called with context.Background(), making it independent of the authentication logic&#39;s context. The login attempt email will be sent even if the authentication times out.</p><h3>🎯 Best Practices for Context Usage</h3><p>To ensure you’re using the context package correctly, keep these best practices in mind:</p><h3>1. Pass Context Explicitly</h3><p>Always pass the context as the first argument to functions. Do not store it in a struct.</p><pre>// ✅ Good<br>func ProcessData(ctx context.Context, data []byte) error {<br>    // ...<br>}<br><br>// ❌ Bad<br>type Worker struct {<br>    ctx context.Context<br>}</pre><h3>2. Never Pass nil Context</h3><p>If you’re unsure what Context to use, pass context.TODO().</p><pre>// ✅ Good<br>ProcessData(context.TODO(), data)<br><br>// ❌ Bad<br>ProcessData(nil, data)</pre><h3>3. Use WithValue Sparingly</h3><p>It should only be used for request-scoped data that must be passed through API boundaries, not for optional parameters. Always use user-defined types for keys to avoid collisions.</p><pre>// ✅ Good - request-scoped data with user-defined key types<br>type contextKey string<br><br>const (<br>    UserIDKey contextKey = &quot;userID&quot;<br>    TraceIDKey contextKey = &quot;traceID&quot;<br>)<br><br>ctx = context.WithValue(ctx, UserIDKey, userID)<br>ctx = context.WithValue(ctx, TraceIDKey, traceID)<br><br>// Helper functions for type-safe retrieval<br>func GetUserID(ctx context.Context) (string, bool) {<br>    userID, ok := ctx.Value(UserIDKey).(string)<br>    return userID, ok<br>}<br><br>func GetTraceID(ctx context.Context) (string, bool) {<br>    traceID, ok := ctx.Value(TraceIDKey).(string)<br>    return traceID, ok<br>}<br><br>// ❌ Bad - using string keys directly (collision risk)<br>ctx = context.WithValue(ctx, &quot;userID&quot;, userID)<br>ctx = context.WithValue(ctx, &quot;traceID&quot;, traceID)<br><br>// ❌ Bad - configuration data<br>ctx = context.WithValue(ctx, &quot;maxRetries&quot;, 3)</pre><h3>4. Always Call Cancel</h3><p>When you create a context with WithCancel, WithTimeout, or WithDeadline, you must call the returned cancel function to release the associated resources.</p><pre>ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)<br>defer cancel() // ✅ Always defer the cancel call</pre><h3>5. Check ctx.Done() in Long Operations</h3><p>In your goroutines, you should select on the ctx.Done() channel to gracefully exit when the context is canceled.</p><pre>func longRunningOperation(ctx context.Context) error {<br>    for {<br>        select {<br>        case &lt;-ctx.Done():<br>            return ctx.Err() // Graceful exit<br>        default:<br>            // Do work<br>            time.Sleep(100 * time.Millisecond)<br>        }<br>    }<br>}</pre><h3>Key Takeaways</h3><p>The context package is a powerful tool for managing concurrent operations in Go, but it requires careful consideration of when and how to use it:</p><ul><li><strong>Use request contexts for request-scoped operations</strong> that should be canceled when the client disconnects</li><li><strong>Create independent contexts for critical operations</strong> that must complete regardless of client state</li><li><strong>Isolate background tasks</strong> with their own contexts to prevent unwanted cancellation propagation</li><li><strong>Understand propagation behavior: </strong>cancellation, deadlines, and values automatically propagate downward from parent to child contexts once derived (e.g., via context.WithCancel, context.WithTimeout, or context.WithValue).</li><li><strong>Always call cancel functions</strong> to prevent resource leaks</li><li><strong>Check ctx.Done() regularly</strong> in long-running operations for graceful shutdowns</li></ul><p>By adhering to these principles and understanding the nuances of context propagation, you can write more robust, efficient, and maintainable concurrent Go applications.</p><p><em>Have you encountered context-related bugs in your Go applications? Share your experiences and solutions in the comments below! 👇</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b568e200345c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Retrieve User Country from IP Address]]></title>
            <link>https://medium.com/@akintobiidris/how-to-retrieve-user-country-from-ip-address-628f4bd6bdb7?source=rss-49ea7a7ba30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/628f4bd6bdb7</guid>
            <category><![CDATA[location]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[maxmind]]></category>
            <category><![CDATA[ip]]></category>
            <dc:creator><![CDATA[Idris Akintobi]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 15:07:45 GMT</pubDate>
            <atom:updated>2025-03-26T15:07:45.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Get user country from ip address" src="https://cdn-images-1.medium.com/max/1024/1*opx1pOyGjNz1YKCqcaiReQ.png" /><figcaption>Get user country from ip address</figcaption></figure><p>While working on a small project that needed to return content based on the user’s country, I found a convenient, free approach to get the user’s country from the IP address in the request object without relying on API calls. However, this approach has its caveats, as you must regularly update your database.</p><p>The approach I will discuss involves using a database provided by <a href="http://maxmind.com/">MaxMind</a> to query IP address information. While there are various types of information you can query, we will focus solely on retrieving the country ISO and city in this article. There are packages that can be used to achieve this, such as <a href="https://www.npmjs.com/package/geoip-lite">geoip-lite</a> or <a href="https://www.npmjs.com/package/fast-geoip">fast-geoip</a>.</p><p>We will explore two approaches: one that requires setting up an account with MaxMind to download the latest data, and another that uses a GitHub repository with a frequently updated downloadable database.</p><p>If you plan to use this service at an enterprise level, please purchase a MaxMind license to access a more accurate and up-to-date database.</p><h3>Using Database from Your MaxMind Account</h3><ol><li><a href="https://www.maxmind.com/en/geolite2/signup">Register for a MaxMind account</a>.</li><li>Create a license key (Optional). This is only needed for updating the database.</li><li>Go to `My Account` and select `Download Database`. Download the database in the format of your choice. We will use the binary (.mmdb) format in this article. Download the zip file and extract it on your server.<br>The CSV format is ideal if you want to dump the data into a database like PostgreSQL or MySQL. You can find the guide to do that <a href="https://dev.maxmind.com/geoip/importing-databases/">here</a>.</li></ol><figure><img alt="Download country binary database" src="https://cdn-images-1.medium.com/max/1024/1*eVh5J25fIGwpBjuE1txbMw.png" /><figcaption>Download country binary database</figcaption></figure><h4>Code Implementation for Country ISO</h4><pre>import { Reader } from &quot;@maxmind/geoip2-node&quot;;<br>import { readFileSync } from &quot;fs&quot;;<br><br>// Synchronous database opening<br>const dbBuffer = readFileSync(&quot;GeoLite2-Country.mmdb&quot;);<br>// This reader object should be reused across lookups as creation of it is expensive.<br>const reader = Reader.openBuffer(dbBuffer);<br><br>const ipAddr = &quot;154.113.170.145&quot;;<br><br>const IP2Country = (ip) =&gt; {<br>  try {<br>    const { country } = reader.country(ip);<br>    return country<br>      ? { countryCode: country.isoCode, country: country.names[&quot;en&quot;] }<br>      : null;<br>  } catch (error) {<br>    console.log(error); // Handle the error as needed. You can make an API call here.<br>    return null;<br>  }<br>};<br><br>console.log(IP2Country(ipAddr));<br>// { countryCode: &quot;NG&quot;, country: &quot;Nigeria&quot; }</pre><p>You can also download the database with city records, which allows you to retrieve city information. Note that the city data may not be available for some IP addresses, so you will need to handle such cases. You should consider purchasing a license to access a more accurate database.</p><figure><img alt="Download city binary database" src="https://cdn-images-1.medium.com/max/1024/1*hYGC9-hhjqhMz_h0AN8o2w.png" /><figcaption>Download city binary database</figcaption></figure><pre>import { Reader } from &quot;@maxmind/geoip2-node&quot;;<br>import { readFileSync } from &quot;fs&quot;;<br><br>// Synchronous database opening<br>const dbBuffer = readFileSync(&quot;GeoLite2-City.mmdb&quot;);<br>// This reader object should be reused across lookups as creation of it is expensive.<br>const reader = Reader.openBuffer(dbBuffer);<br><br>const ipAddr = &quot;154.113.170.145&quot;;<br><br>const IP2City = (ip) =&gt; {<br>  try {<br>    const { country, city, continent } = reader.city(ip);<br>    return {<br>      city: city?.names[&quot;en&quot;],<br>      country: country?.names[&quot;en&quot;],<br>      countryCode: country?.isoCode,<br>      continent: continent?.names[&quot;en&quot;],<br>    };<br>  } catch (error) {<br>    console.log(error); // Handle the error as needed. You can make an API call here.<br>    return null;<br>  }<br>};<br><br>console.log(IP2City(ipAddr));<br>// { city: &quot;Lagos&quot;, country: &quot;Nigeria&quot;, countryCode: &quot;NG&quot;, continent: &quot;Africa&quot; }</pre><p>The city database is quite large and can be resource-intensive to load into memory, depending on your server resources. If city data is necessary for your service, I recommend downloading the CSV database and importing it into your database to query. The guide can be found <a href="https://dev.maxmind.com/geoip/importing-databases/postgresql/">here</a>.</p><h3>Using Database from Sapic IP-Location-DB GitHub Repository</h3><p>This approach does not require setting up a MaxMind account, as the database files are already available in the repository and are frequently updated.</p><ol><li>Go to the [repository](<a href="https://github.com/sapics/ip-location-db">https://github.com/sapics/ip-location-db</a>) and select <a href="https://github.com/sapics/ip-location-db/tree/main/geolite2-country-mmdb">geolite2-country-mmdb</a> to download the database. We will be using the IPv4 binary database, but you can also download the IPv6 database and implement the function if needed.</li></ol><figure><img alt="Download country binary database" src="https://cdn-images-1.medium.com/max/1024/1*PpyWPRk3YljfT_Ns66fVSg.png" /><figcaption>Download country binary database</figcaption></figure><p>This minimal database is resource-efficient, as the data loaded into memory is smaller.</p><h4>Code Implementation for Country ISO (Using Sapic Repository)</h4><pre>import { readFileSync } from &quot;fs&quot;;<br>import { Reader } from &quot;maxmind&quot;;<br><br>// Synchronous database opening<br>const dbBuffer = readFileSync(&quot;geolite2-country-ipv4.mmdb&quot;);<br>// This reader object should be reused across lookups as creation of it is expensive.<br>const reader = new Reader(dbBuffer);<br><br>const ipAddr = &quot;154.113.170.145&quot;;<br><br>const IP2Country = (ip) =&gt; {<br>  try {<br>    return { countryCode: reader.get(ip).country_code };<br>  } catch (error) {<br>    console.log(error); Handle the error as needed. You can make an API call here.<br>  }<br>};<br><br>console.log(IP2Country(ipAddr));<br>// { countryCode: &quot;NG&quot; }</pre><figure><img alt="Download city binary database" src="https://cdn-images-1.medium.com/max/1024/1*8_C7saa6l4PKDQgQmJvk3A.png" /><figcaption>Download city binary database</figcaption></figure><h4>Code Implementation for City Information (Using Sapic Repository)</h4><pre>import { readFileSync } from &quot;fs&quot;;<br>import { Reader } from &quot;maxmind&quot;;<br><br>// Synchronous database opening<br>const dbBuffer = readFileSync(&quot;geolite2-city-ipv4.mmdb&quot;);<br>// This reader object should be reused across lookups as creation of it is expensive.<br>const reader = new Reader(dbBuffer);<br><br>const ipAddr = &quot;154.113.170.145&quot;;<br><br>const IP2City = (ip) =&gt; {<br>  try {<br>    const { city, country_code } = reader.get(ip);<br>    return { city, countryCode: country_code };<br>  } catch (error) {<br>    console.log(error); // Handle the error as needed. You can make an API call here.  }<br>};<br><br>console.log(IP2City(ipAddr));<br>// { city: &quot;Lagos&quot;, countryCode: &quot;NG&quot; }</pre><h3>Conclusion</h3><p>In this article, we explored two ways to retrieve country and city data from an IP address without relying on API requests. Both methods involve using a local database that needs to be updated regularly to ensure new IP addresses are included. It is essential to automate the process of downloading the latest database and updating your local copy, as MaxMind updates its GeoLite2 database every Tuesday and Friday. You should set up a job that runs to update your database and keep in mind that the database size will grow as it is being updated. [Here is a solution created by MaxMind](<a href="https://dev.maxmind.com/geoip/updating-databases">https://dev.maxmind.com/geoip/updating-databases</a>).</p><p>Ensure you abide by MaxMind’s terms of service when using the data, and consider purchasing a license for more accurate and up-to-date information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=628f4bd6bdb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Step-by-Step Guide to Google OAuth2 Authentication with JavaScript]]></title>
            <link>https://medium.com/@akintobiidris/a-step-by-step-guide-to-google-oauth2-authentication-with-javascript-d8a8d520adde?source=rss-49ea7a7ba30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8a8d520adde</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[bunjs]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Idris Akintobi]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 07:29:22 GMT</pubDate>
            <atom:updated>2025-02-07T07:48:59.254Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Guide to Google OAuth2 Authentication with JavaScript" src="https://cdn-images-1.medium.com/max/1000/1*AKtDrhQZ3d1zbAJlAeWfig.png" /><figcaption>Guide to Google OAuth2 Authentication with JavaScript</figcaption></figure><p>When it comes to authenticating users with Google, OAuth2 provides a secure and standardized approach. While there are libraries that abstract much of the process, this article walks you through a foundational implementation using JavaScript and an Express server. By the end, you’ll understand the underlying concepts and have a running example of Google OAuth2.</p><p>The project can be run with any JavaScript runtime like Node or Deno, but we are using <strong>Bun</strong> (a fast, modern JavaScript runtime) to run our project.</p><h3>Setting Up Google OAuth2</h3><p>Before diving into the code, configure your project in the Google Cloud Console.</p><h4>Step 1: Create a Google Cloud Project</h4><ol><li>Visit <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</li><li>Create a new project if you do not have an existing one.</li></ol><figure><img alt="Create a Google Cloud Project" src="https://cdn-images-1.medium.com/max/1024/1*FP-FXpTDCvhL7EZgWPi7-g.png" /><figcaption>Create a Google Cloud Project</figcaption></figure><h4>Step 2: Configure OAuth Consent Screen</h4><ol><li>Navigate to <strong>API &amp; Services &gt; OAuth Consent Screen</strong> to configure your application.</li><li>Fill in the necessary details like app name and support email.</li></ol><figure><img alt="Configure Google OAuth Consent Screen" src="https://cdn-images-1.medium.com/max/1024/1*QmGIxwoWrbctvBz5xTszzw.png" /><figcaption>Configure Google OAuth Consent Screen</figcaption></figure><p>3. Customize branding (optional) to provide more details about your app’s consent screen.</p><figure><img alt="Customize Google OAuth branding" src="https://cdn-images-1.medium.com/max/1024/1*mjzcKKCTLBT_TDEuawbk9w.png" /><figcaption>Customize Google OAuth branding</figcaption></figure><h4>Step 3: Set Up Scopes</h4><ol><li>Under the <strong>Scopes</strong> section, add:</li></ol><ul><li>email: Access the user’s email address.</li><li>openid: OpenID Connect scope for identity verification.</li><li>profile: Access basic profile information like name and picture.</li></ul><figure><img alt="Set Up Google OAuth Scopes" src="https://cdn-images-1.medium.com/max/1024/1*yoAZowVTcUBuQHAq6hxmYg.png" /><figcaption>Set Up Google OAuth Scopes</figcaption></figure><h4>Step 4: Create OAuth Client ID</h4><p>It might take a few minutes before you can create a client ID.</p><ol><li>Go to <strong>Credentials &gt; Create Credentials &gt; OAuth Client ID</strong>.</li><li>Select <strong>Web Application</strong> as the application type.</li><li>Set the <strong>Authorized JavaScript Origin</strong> to <a href="http://localhost:3000.">http://localhost:3000.</a></li><li>Add a <strong>Redirect URI</strong>: http://localhost:3000. Replace these with your hosted URI when deploying to production.</li></ol><figure><img alt="Create Google OAuth Client ID" src="https://cdn-images-1.medium.com/max/1024/1*dBDKf-LIDbNAGYuqF858MA.png" /><figcaption>Create Google OAuth Client ID</figcaption></figure><p>Google will redirect users to the <strong>Redirect URI</strong> after authentication, appending an authorization code and state parameters. The redirect URI can be another page or the backend service. For simplicity, we are using the same page to handle the authenticated user code.</p><figure><img alt="Google OAuth Client ID" src="https://cdn-images-1.medium.com/max/1024/1*AaNjUvXBQa6deovj3O_6vw.png" /><figcaption>Google OAuth Client ID</figcaption></figure><h4>Step 5: Add Test Users</h4><p>In test mode, you must explicitly add the email addresses of users you want to test the flow with. You should publish your app once you’re satisfied with the test.</p><figure><img alt="Add Test Users To Google OAuth Client" src="https://cdn-images-1.medium.com/max/1024/1*wpeQVopmiyRuW5c2XY-h-g.png" /><figcaption>Add Test Users To Google OAuth Client</figcaption></figure><h3>Coding the Google OAuth2 Implementation</h3><h3>Project Setup</h3><ol><li><strong>Install Bun</strong>:<br>If you don’t have Bun installed, follow the instructions at <a href="https://bun.sh/">bun.sh</a>. We are using Bun version 1.2.</li><li><strong>Initialize the Project</strong>:<br>Create a new directory for your project and initialize it with Bun:</li></ol><pre>mkdir google-oauth-express<br>cd google-oauth-express<br>bun init</pre><h4>Folder Structure</h4><p>Organize your project as follows:</p><pre>project/<br>├── public/<br>│   └── index.html<br>├── src/<br>│   └── index.js<br>├── .env<br>└── bun.lock</pre><p>3. <strong>Install Dependencies:<br></strong>Install the required dependencies:</p><pre>bun add express google-auth-library</pre><p>4. <strong>Set Environment Variables: </strong><br> Create a `.env` file and add:</p><pre>GOOGLE_CLIENT_ID=your_google_client_id<br>GOOGLE_CLIENT_SECRET=your_google_client_secret<br>GOOGLE_REDIRECT_URI=http://localhost:3000</pre><h3>index.html</h3><p>The HTML file provides a simple interface for initiating Google Sign-In and handling the OAuth redirect.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;Google OAuth Test App&lt;/title&gt;<br>    &lt;script&gt;<br>    //   Function to capture URL parameters and handle the OAuth redirect<br>    // If you&#39;re using React, you can have this run on page load effect<br>      function handleOAuthCallback() {<br>        const urlParams = new URLSearchParams(window.location.search);<br>        const code = urlParams.get(&quot;code&quot;);<br>        const state = urlParams.get(&quot;state&quot;);<br>        const error = urlParams.get(&quot;error&quot;);<br><br>        if (code &amp;&amp; state) {<br>          // Check the CSRF token<br>          const storedState = localStorage.getItem(&quot;oauth_state&quot;);<br>          if (state === storedState) {<br>            // Send the code to the server for token exchange<br>            // For security reason you should have some logic on the backend to ensure requests only come from your apps. Such as using CORS for web apps.<br>            fetch(&quot;/auth/google/login&quot;, {<br>              method: &quot;POST&quot;,<br>              headers: {<br>                &quot;Content-Type&quot;: &quot;application/json&quot;,<br>              },<br>              body: JSON.stringify({ code }),<br>            })<br>              .then((response) =&gt; response.json())<br>              .then((data) =&gt; {<br>                console.log(&quot;Success:&quot;, data);<br>              })<br>              .catch((error) =&gt; {<br>                console.error(&quot;Error:&quot;, error);<br>              });<br>          } else if (error) {<br>            console.error(&quot;Authentication failed&quot;, error);<br>          } else {<br>            console.error(&quot;State mismatch&quot;);<br>          }<br>        }<br>      }<br><br>      // Call the function when the page loads<br>      handleOAuthCallback();<br>    &lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Google OAuth Test App&lt;/h1&gt;<br>    &lt;button id=&quot;google-signin-button&quot;&gt;Sign in with Google&lt;/button&gt;<br><br>    &lt;script&gt;<br>      const GOOGLE_OAUTH_URL = &quot;https://accounts.google.com/o/oauth2/v2/auth&quot;;<br>      const GOOGLE_CLIENT_ID = &quot;your_google_client_id&quot;; // Replace with your client ID<br>      const GOOGLE_CALLBACK_URL = &quot;http://localhost:3000&quot;;<br>      const GOOGLE_OAUTH_SCOPES = [<br>        &quot;https://www.googleapis.com/auth/userinfo.email&quot;,<br>        &quot;https://www.googleapis.com/auth/userinfo.profile&quot;,<br>      ];<br><br>      // Function to generate the OAuth URL and redirect the user<br>      function initiateGoogleOAuth() {<br>        const state = crypto.randomUUID(); // Generate a CSRF token<br>        localStorage.setItem(&quot;oauth_state&quot;, state);<br><br>        const params = new URLSearchParams({<br>          client_id: GOOGLE_CLIENT_ID,<br>          redirect_uri: GOOGLE_CALLBACK_URL,<br>          access_type: &quot;offline&quot;,<br>          response_type: &quot;code&quot;,<br>          state: state,<br>          scope: GOOGLE_OAUTH_SCOPES.join(&quot; &quot;),<br>        });<br><br>        const GOOGLE_OAUTH_CONSENT_SCREEN_URL = `${GOOGLE_OAUTH_URL}?${params.toString()}`;<br>        window.location.href = GOOGLE_OAUTH_CONSENT_SCREEN_URL;<br>      }<br><br>      // Attach the function to the button click event<br>      document<br>        .getElementById(&quot;google-signin-button&quot;)<br>        .addEventListener(&quot;click&quot;, initiateGoogleOAuth);<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>index.js</h3><p>This file handles the server-side implementation of Google OAuth2.</p><pre>import express from &quot;express&quot;;<br>import { OAuth2Client } from &quot;google-auth-library&quot;;<br><br>const app = express();<br><br>app.use(express.static(&quot;public&quot;));<br>app.use(express.json());<br><br>const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;<br>const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;<br>const GOOGLE_REDIRECT_URI = process.env.GOOGLE_REDIRECT_URI;<br><br>if (!GOOGLE_CLIENT_ID || !GOOGLE_CLIENT_SECRET || !GOOGLE_REDIRECT_URI) {<br>  throw new Error(&quot;Missing required environment variables for Google OAuth.&quot;);<br>}<br><br>const googleClient = new OAuth2Client(GOOGLE_CLIENT_ID);<br><br>// Middleware to check if the user is authenticated<br>async function isAuthenticated(req, res, next) {<br>  const token = req.headers.authorization?.split(&quot; &quot;)[1]; // Extract token from &quot;Bearer &lt;token&gt;&quot;<br><br>  if (!token) {<br>    return res.status(401).json({ message: &quot;Unauthorized: No token provided&quot; });<br>  }<br><br>  try {<br>    // This is to verify the google id_token.<br>    const ticket = await googleClient.verifyIdToken({<br>      idToken: token,<br>      audience: GOOGLE_CLIENT_ID,<br>    });<br><br>    const payload = ticket.getPayload();<br>    req.user = payload;<br>    next();<br>  } catch (error) {<br>    console.error(&quot;Token verification failed:&quot;, error);<br>    res.status(401).json({ message: &quot;Unauthorized: Invalid token&quot; });<br>  }<br>}<br><br>// Route to handle Google OAuth login<br>app.post(&quot;/auth/google/login&quot;, async (req, res) =&gt; {<br>  const { code } = req.body;<br><br>  if (!code) {<br>    return res.status(401).json({ message: &quot;Unauthorized&quot; });<br>  }<br><br>  try {<br>    const response = await fetch(&quot;https://oauth2.googleapis.com/token&quot;, {<br>      method: &quot;POST&quot;,<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      },<br>      body: JSON.stringify({<br>        code,<br>        client_id: GOOGLE_CLIENT_ID,<br>        client_secret: GOOGLE_CLIENT_SECRET,<br>        redirect_uri: GOOGLE_REDIRECT_URI,<br>        grant_type: &quot;authorization_code&quot;,<br>      }),<br>    }).then((res) =&gt; res.json());<br><br>    // The `response` object contains id_token which is a jwt token with the payload of the user information. If you have existing application authorization logic<br>    // you can use it here by checking if the email address in the jwt payload exists in your database and return the authorization token to the user.<br>    // In this article we are using the id_token provided by google as the authorization token.<br>    res.json({ token: response.id_token });<br>  } catch (error) {<br>    console.error(&quot;Error during token exchange:&quot;, error);<br>    res.status(500).json({ message: &quot;Failed to authenticate with Google&quot; });<br>  }<br>});<br><br>// Protected route example<br>app.get(&quot;/protected&quot;, isAuthenticated, (req, res) =&gt; {<br>  res.json({ message: &quot;You are authenticated!&quot;, user: req.user });<br>});<br><br>const PORT = process.env.PORT || 3000;<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is listening on port ${PORT}`);<br>});</pre><h3>Running the Project</h3><ol><li><strong>Run the Server</strong>: <br> Execute the following command:</li></ol><pre>bun run src/index.js</pre><p>2. <strong>Test the Flow</strong>:<br> — Open `<a href="http://localhost:3000`">http://localhost:3000`</a> in your browser.<br> — Click <strong>Sign in with Google</strong>.<br> — Authenticate with your Google account.<br> — Check the console for the token.<br> — Use the bearer token to access the /protected route.</p><h3>Conclusion</h3><p>This implementation provides a solid understanding of Google OAuth2 and can be ported to other frameworks or production-ready applications. While tools like `passport` or `next-auth` simplify OAuth2, building it manually ensures you understand how authentication works under the hood.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8a8d520adde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Paystack for Subscription-Based Billing in NestJS]]></title>
            <link>https://medium.com/@akintobiidris/setting-up-paystack-for-subscription-based-billing-in-nestjs-481c4733dfb5?source=rss-49ea7a7ba30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/481c4733dfb5</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[paystack]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[payments]]></category>
            <dc:creator><![CDATA[Idris Akintobi]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 18:59:20 GMT</pubDate>
            <atom:updated>2024-12-23T18:59:20.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*J7suvHrj1MUPUecBWVP4AA.png" /><figcaption>nestjs-paystack</figcaption></figure><p>Subscriptions are integral to many applications, enabling recurring billing for customers. This tutorial walks you through integrating <strong>Paystack</strong> for subscription-based billing using <strong>NestJS</strong>, providing insights into key steps, potential pitfalls, and best practices.</p><h3>1. Understanding Paystack’s Subscription Model</h3><p>Before diving into the code, let’s clarify some basics:</p><ul><li><strong>Account Setup</strong>: Create a Paystack account. Note that, as at the time of writing this article, Paystack accepts account creation per currency and supports only a few countries. Confirm if your country and currency are supported.</li><li><strong>Currency Handling</strong>: A business operating in multiple currencies needs separate accounts for each. Payments in foreign currencies update your account balance in your default currency unless specified otherwise. Reach out to Paystack support for clarification.</li><li><strong>Testing Mode</strong>: Always test in <strong>Test Mode</strong> before switching to <strong>Live Mode</strong>.</li></ul><h3>2. Bootstrapping the NestJS Application</h3><p>Let’s start by creating a new NestJS project using the Nest CLI:</p><pre>nest new paystack-nestjs --strict</pre><p>Move into the project directory:</p><pre>cd paystack-nestjs</pre><p>For simplicity, we’ll leave the default files intact and focus on implementing our features.</p><h3>3. Managing Environment Variables</h3><p>We’ll use the @nestjs/config package to manage environment variables:</p><pre>npm i --save @nestjs/config</pre><p>Import the ConfigModule into the application module to make environment variables accessible.</p><figure><img alt="Add configModule to the AppModule" src="https://cdn-images-1.medium.com/max/923/1*31A0zNw21SHstNKHVtD03Q.png" /><figcaption>Add configModule to the AppModule</figcaption></figure><h4>Setting Up Environment Variables</h4><p>Create a .env file:</p><pre>touch .env &amp;&amp; echo &quot;\n.env&quot; &gt;&gt; .gitignore</pre><p>Add the following variables:</p><pre>PAYSTACK_SECRET=your_paystack_secret_key<br>PAYSTACK_BASE_URL=https://api.paystack.co<br>PAYSTACK_SUCCESS_URL=https://example.com #Page the customer will be redirected to after a successful charge.</pre><p>Retrieve the secret key from the <strong>API &amp; Webhooks</strong> tab on the Paystack.</p><figure><img alt="Retrieve paystack secret key" src="https://cdn-images-1.medium.com/max/1024/1*tgWCC9bCkUb7AKfO30iVdg.png" /><figcaption>Retrieve paystack secret key</figcaption></figure><h3>4. Webhook Configuration</h3><p>Paystack uses webhooks to notify your system for events like successful charges. You can use w<a href="https://webhook.site/">ebhook.site</a> to view and confirm that the payloads were received.</p><ul><li>Generate a webhook URL and paste it into the Paystack <strong>Webhook</strong> field.</li><li>Save your changes and keep the Webhook.site page open to monitor events.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQ8S7Ou6PssBURAWBlUCDQ.png" /><figcaption>Webhook site</figcaption></figure><h3>5. Creating a Subscription Plan</h3><p>To enable subscriptions, create a plan in Paystack:</p><ul><li>Set the plan interval and maximum charges or leave it untouched for continuous billing.</li></ul><figure><img alt="Create paystack plan" src="https://cdn-images-1.medium.com/max/1024/1*wNIq64FHFajEjw8M45Lm5Q.png" /><figcaption>Create paystack plan</figcaption></figure><h3>6. Implementing Paystack Client</h3><p>Generate a PaystackClient class to handle API calls:</p><pre>nest generate class paystack/PaystackClient --no-spec --flat</pre><p>Install Axios to make HTTP requests:</p><pre>npm install --save axios</pre><h4>PaystackClient Methods</h4><p>The client will include:</p><ul><li>createCustomer: Registers a customer on Paystack.</li><li>findCustomerByEmail: Searches for a customer using their email.</li><li>listSubscriptions: Lists active customer subscriptions.</li><li>initializeTransaction: Creates a payment link for customer charge authorization. Various payment methods is available. This is enough if you only want a one time payment because you can set the amount you want to charge the customer in the request.</li><li>initializeSubscription: Creates a payment link for customer charge authorization. This is to charge and subscribe a customer a plan. We are passing the planId here which the plan cost will override any amount set in the request. Only card payment is available with this.</li><li>getSubscription: Fetches subscription details by ID.</li><li>createSubscription: Subscribes a customer to a plan.</li><li>cancelSubscription: Cancels an active subscription.</li></ul><pre>import { BadRequestException, Injectable, InternalServerErrorException, Logger } from &#39;@nestjs/common&#39;;<br>import { ConfigService } from &#39;@nestjs/config&#39;;<br>import axios, { AxiosInstance } from &#39;axios&#39;;<br>import type { Customer } from &#39;src/types/dtos&#39;;<br>import type {<br>    CustomerResponseDTO,<br>    PaystackCustomer,<br>    PaystackPaymentSessionResponse,<br>    PaystackPaymentSessionResult,<br>    PlanResponse,<br>    SubscriptionData,<br>    SubscriptionResponse,<br>} from &#39;src/types/paystack-api-types&#39;;<br><br>@Injectable()<br>export class PaystackClient {<br>    private readonly httpInstance: AxiosInstance;<br><br>    private readonly checkoutSuccessUrl: string;<br><br>    private readonly logger: Logger;<br><br>    public constructor(private readonly configService: ConfigService) {<br>        this.httpInstance = axios.create({<br>            baseURL: this.configService.get(&#39;PAYSTACK_BASE_URL&#39;),<br>            headers: {<br>                Authorization: `Bearer ${this.configService.get(&#39;PAYSTACK_SECRET&#39;)}`,<br>                &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            },<br>        });<br>        this.logger = new Logger(&#39;PAYSTACK CLIENT&#39;);<br>        this.checkoutSuccessUrl = this.configService.get(&#39;PAYSTACK_SUCCESS_URL&#39;);<br>    }<br><br>    async createCustomer(customerData: Customer): Promise&lt;PaystackCustomer&gt; {<br>        try {<br>            const { data } = await this.httpInstance.post&lt;CustomerResponseDTO&gt;(&#39;/customer&#39;, {<br>                first_name: customerData.firstName,<br>                last_name: customerData.lastName,<br>                email: customerData.email,<br>                phone: customerData.phoneNumber,<br>            });<br><br>            return data.data;<br>        } catch (e) {<br>            this.handleError(e);<br>        }<br>    }<br><br>    async findCustomerByEmail(email: string): Promise&lt;PaystackCustomer&gt; {<br>        try {<br>            const { data } = await this.httpInstance.get&lt;CustomerResponseDTO&gt;(`/customer/${email}`);<br>            return data.data;<br>        } catch (e) {<br>            this.handleError(e);<br>        }<br>    }<br><br>    async listSubscriptions(email: string): Promise&lt;SubscriptionData[] | null&gt; {<br>        const { subscriptions } = await this.findCustomerByEmail(email);<br><br>        return subscriptions.length ? subscriptions : null;<br>    }<br><br>    /**<br>     * This method is to initialize a charge transaction. We need to pass the amount that we want the customer to be charged.<br>     * Various payment method is available.<br>     * We concatenate the planId and transactionId as the value to the reference because we will need the planId to subscribe the user to the plan when the webhook event is received.<br>     */<br>    async initializeTransaction(<br>        customerEmail: string,<br>        planId: string,<br>        transactionId: string,<br>    ): Promise&lt;PaystackPaymentSessionResult&gt; {<br>        try {<br>            const planCost = await this.getPlanCost(planId);<br>            const { data } = await this.httpInstance.post&lt;PaystackPaymentSessionResponse&gt;(&#39;/transaction/initialize&#39;, {<br>                email: customerEmail,<br>                amount: planCost,<br>                reference: planId + &#39;__&#39; + transactionId,<br>                callback_url: this.checkoutSuccessUrl + &#39;?&#39; + transactionId, // This is to add the transactionId as a query parameter to the checkoutSuccessUrl<br>            });<br><br>            return {<br>                authorizationUrl: data.data.authorization_url,<br>                accessCode: data.data.access_code,<br>                reference: data.data.reference,<br>            };<br>        } catch (e) {<br>            this.handleError(e);<br>        }<br>    }<br><br>    /**<br>     * This method is to charge a customer and subscribe them to a plan.<br>     * Only card payment is allowed. Other payment methods can not be charged automatically<br>     */<br>    async initializeSubscription(<br>        customerEmail: string,<br>        planId: string,<br>        transactionId: string,<br>    ): Promise&lt;PaystackPaymentSessionResult&gt; {<br>        try {<br>            const { data } = await this.httpInstance.post&lt;PaystackPaymentSessionResponse&gt;(&#39;/transaction/initialize&#39;, {<br>                email: customerEmail,<br>                plan: planId,<br>                reference: transactionId,<br>                callback_url: this.checkoutSuccessUrl + &#39;?&#39; + transactionId,<br>            });<br><br>            return {<br>                authorizationUrl: data.data.authorization_url,<br>                accessCode: data.data.access_code,<br>                reference: data.data.reference,<br>            };<br>        } catch (e) {<br>            this.handleError(e);<br>        }<br>    }<br><br>    async getSubscription(id: string): Promise&lt;SubscriptionData&gt; {<br>        try {<br>            const { data } = await this.httpInstance.get&lt;SubscriptionResponse&gt;(`/subscription/${id}`);<br>            return data.data;<br>        } catch (e) {<br>            this.handleError(e);<br>        }<br>    }<br><br>    async createSubscription(customerId: string, planId: string): Promise&lt;void&gt; {<br>        try {<br>            await this.httpInstance.post&lt;SubscriptionResponse&gt;(&#39;/subscription/&#39;, {<br>                customer: customerId,<br>                plan: planId,<br>            });<br>        } catch (e) {<br>            this.handleError(e);<br>        }<br>    }<br><br>    async cancelSubscription(subCode: string, emailToken: string): Promise&lt;void&gt; {<br>        try {<br>            await this.httpInstance.post(`/subscription/disable`, {<br>                code: subCode,<br>                token: emailToken,<br>            });<br>        } catch (e) {<br>            this.handleError(e);<br>        }<br>    }<br><br>    /**<br>     * This is a function to get the cost of a plan.<br>     * For simplicity a map can be used but we want a single source of truth.<br>     */<br>    private async getPlanCost(id: string): Promise&lt;string&gt; {<br>        try {<br>            const { data } = await this.httpInstance.get&lt;PlanResponse&gt;(`/plan/${id}`);<br>            return data.data.amount.toString();<br>        } catch (e) {<br>            if (axios.isAxiosError(e)) {<br>                this.handleError(e);<br>            }<br>        }<br>    }<br><br>    private handleError(e: Error) {<br>        if (axios.isAxiosError(e)) {<br>            const response = e.response?.data as Record&lt;string, unknown&gt;;<br>            this.logger.warn(&#39;Paystack API error&#39;, JSON.stringify(response));<br>            throw new BadRequestException(response.message || &#39;Paystack API error&#39;);<br>        }<br>        throw new InternalServerErrorException((e as Error).message);<br>    }<br>}</pre><p>We will be using the initializeTransaction in our implementation because we want to be able to show various payment methods to our customers and manually subscribe them to the plan when we receive the charge.success event. We had to concatenate the planId and unique transactionId with the separator __ because the charge.success event payload will not contain any plan details if initializeTransaction method was used.<br>With this implementation, auto renewal will only be applicable to users who has the card authorization; user who paid with their cards.</p><h3>7. Building the Paystack Service</h3><p>Generate the Paystack service:</p><pre>nest generate service paystack/Paystack --no-spec --flat</pre><h4>PaystackService Methods</h4><p>This service will include:</p><ul><li>createPaymentSession: Generates an authorization URL for the customer.</li><li>cancelSubscription: Cancels an active subscription.</li></ul><pre>import { BadRequestException, Inject, Injectable, Logger } from &#39;@nestjs/common&#39;;<br>import { PaystackEvents } from &#39;src/types/enums&#39;;<br>import { PaystackPaymentSessionResult, PaystackWebhookPayload } from &#39;src/types/paystack-api-types&#39;;<br>import { PaystackPaymentSessionDTO } from &#39;../types/dtos&#39;;<br>import { PaystackClient } from &#39;./paystack-client&#39;;<br><br>@Injectable()<br>export class PaystackService {<br>    private readonly logger: Logger;<br><br>    constructor(@Inject(PaystackClient) private readonly client: PaystackClient) {<br>        this.logger = new Logger(&#39;PAYSTACK SERVICE&#39;);<br>    }<br><br>    public async createPaymentSession(<br>        paymentSession: PaystackPaymentSessionDTO,<br>    ): Promise&lt;PaystackPaymentSessionResult&gt; {<br>        this.logger.localInstance;<br>        if (!paymentSession.planId) {<br>            throw new BadRequestException(&#39;Paystack Plan ID is required&#39;);<br>        }<br><br>        if (!paymentSession.transactionId) {<br>            throw new BadRequestException(&#39;transaction ID is required&#39;);<br>        }<br><br>        const customer = await this.client.createCustomer(paymentSession.customer);<br><br>        const activeSubscriptionResult = await this.client.listSubscriptions(customer.email);<br><br>        if (activeSubscriptionResult) {<br>            throw new BadRequestException(&#39;customer already has an active subscription&#39;);<br>        }<br><br>        const subscriptionResponse = await this.client.initializeTransaction(<br>            paymentSession.customer.email,<br>            paymentSession.planId,<br>            paymentSession.transactionId,<br>        );<br><br>        return subscriptionResponse;<br>    }<br><br>    // In our implementation, the customer can only be subscribed to a plan at a time.<br>    //There will only be one active subscription for a customer and they can cancel it if they want to subscribe to another plan.<br>    public async cancelSubscription(email: string): Promise&lt;void&gt; {<br>        const customerSubscriptions = await this.client.listSubscriptions(email);<br>        if (!customerSubscriptions) {<br>            throw new BadRequestException(&#39;User have no active subscription&#39;);<br>        }<br><br>        const activeSubscriptions = customerSubscriptions[0];<br>        await this.client.cancelSubscription(activeSubscriptions.subscription_code, activeSubscriptions.email_token);<br>    }</pre><h3>8. Creating the Controller</h3><p>Generate a controller for the service:</p><pre>nest generate controller paystack/Paystack --no-spec --flat</pre><p>The controller will include /create endpoint to handle payment session creation requests.</p><pre>import { Body, Controller, Inject, Post } from &#39;@nestjs/common&#39;;<br>import { PaystackPaymentSessionDTO } from &#39;src/types/dtos&#39;;<br>import { PaystackService } from &#39;./paystack.service&#39;;<br><br>@Controller(&#39;paystack&#39;)<br>export class PaystackController {<br>    constructor(@Inject(PaystackService) private readonly paystackService: PaystackService) {}<br><br>    @Post(&#39;/create&#39;)<br>    async createPaymentSession(@Body() body: PaystackPaymentSessionDTO) {<br>        return await this.paystackService.createPaymentSession(body);<br>    }<br>}</pre><figure><img alt="Successful create subscription request" src="https://cdn-images-1.medium.com/max/1024/1*ETZLAHABl13UBtUCcGLLtw.png" /><figcaption>Successful create subscription request</figcaption></figure><h3>9. Handling Webhooks</h3><h4>Webhook Payload Handling</h4><p>When a charge succeeds, We need to subscribe the user to the plan. We can get the planId to subscribe the customer to from the reference by separating it with __. We have created the customer record and it is updated with their payment authorization after the charge.</p><ul><li><strong>Event Handling</strong>: We will handle events charge.success and subscription.create events.</li></ul><p>Update the Paystack service with a handleWebhookEvents method to process these events and update the controller with the route to handle webhook events.</p><figure><img alt="Handle webhookEvents code" src="https://cdn-images-1.medium.com/max/943/1*XgZNryEA0-qK4AJ2Y2ONRw.png" /><figcaption>handleWebhookEvents code</figcaption></figure><figure><img alt="Add webhook-events route" src="https://cdn-images-1.medium.com/max/819/1*y_T9BaE5PbCCkE_JCfiq5w.png" /><figcaption>Add webhook-events route</figcaption></figure><h4>Securing Webhooks</h4><p>Use x-paystack-signature in there webhook event request to verify payload authenticity. Add the rawBody option to your application to ensure you can get the raw request body:</p><figure><img alt="Set rawBody to true in application instance" src="https://cdn-images-1.medium.com/max/649/1*YiXERb9psno1tU8SWP7BHw.png" /><figcaption>Set rawBody to true in application instance</figcaption></figure><p>Generate a guard for signature validation:</p><pre>nest generate guard paystack/PaystackWebhook --no-spec --flat</pre><pre>import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from &#39;@nestjs/common&#39;;<br>import { ConfigService } from &#39;@nestjs/config&#39;;<br>import * as crypto from &#39;crypto&#39;;<br><br>@Injectable()<br>export class PaystackWebhookGuard implements CanActivate {<br>    constructor(private readonly config: ConfigService) {}<br><br>    async canActivate(context: ExecutionContext): Promise&lt;boolean&gt; {<br>        const http = context.switchToHttp();<br>        const request = http.getRequest();<br>        const secret = this.config.get&lt;string&gt;(&#39;PAYSTACK_SECRET&#39;);<br><br>        const signature = request.headers[&#39;x-paystack-signature&#39;];<br>        if (!signature) {<br>            throw new UnauthorizedException(&#39;No signature provided&#39;);<br>        }<br><br>        const hash = crypto.createHmac(&#39;sha512&#39;, secret).update(JSON.stringify(request.body)).digest(&#39;hex&#39;);<br><br>        const signatureBuffer = Buffer.from(signature);<br>        const hashBuffer = Buffer.from(hash);<br><br>        try {<br>            const isValid =<br>                signatureBuffer.length === hashBuffer.length &amp;&amp; crypto.timingSafeEqual(signatureBuffer, hashBuffer);<br><br>            if (!isValid) {<br>                throw new UnauthorizedException(&#39;Invalid signature&#39;);<br>            }<br><br>            return true;<br>        } catch (error) {<br>            throw new UnauthorizedException(&#39;Invalid signature&#39;);<br>        }<br>    }<br>}</pre><p>Add the guard to the webhook-event route</p><figure><img alt="Add guard to webhook-events route" src="https://cdn-images-1.medium.com/max/827/1*DksRvmkcz88n_roxH0Y7vA.png" /><figcaption>Add guard to webhook-events route</figcaption></figure><h3>10. Testing and Deployment</h3><ul><li>You can host the service publicly or use VS Code port forwarding tunnels for testing.</li><li>Update the webhook URL on Paystack with your public endpoint.</li></ul><figure><img alt="Update paystack webhook url" src="https://cdn-images-1.medium.com/max/1024/1*DNyXZWumhmSvN2PxirnfpA.png" /><figcaption>Update paystack webhook url</figcaption></figure><h4>Final Checks</h4><p>Simulate a payment, monitor webhook logs, and confirm subscription creation on the Paystack dashboard.</p><figure><img alt="Test webhook implementation" src="https://cdn-images-1.medium.com/max/1024/1*CXeBGJd9zEQcnKYN97yxlg.png" /><figcaption>Test webhook implementation</figcaption></figure><h3>Conclusion</h3><p>This guide covered integrating Paystack for subscription billing in a NestJS application. We explored creating subscriptions, handling webhooks, and securing webhook endpoints. While we focused on the basics, additional steps like proper logging, error handling, and input validation are crucial for production environments.</p><p>You can find the complete code for this implementation on GitHub: <a href="https://github.com/IdrisAkintobi/paystack-subscription-nestjs">https://github.com/IdrisAkintobi/paystack-subscription-nestjs</a>.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=481c4733dfb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a SOCKS Proxy Server with Dante on AWS]]></title>
            <link>https://medium.com/@akintobiidris/setting-up-a-socks-proxy-server-with-dante-on-aws-dc4ce6f95bae?source=rss-49ea7a7ba30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc4ce6f95bae</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Idris Akintobi]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 23:22:55 GMT</pubDate>
            <atom:updated>2024-01-12T00:14:47.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Setting up a SOCKS Proxy Server with Dante on AWS" src="https://cdn-images-1.medium.com/max/1024/1*Tnz1Ee0NqVT2nFTSUe_JPw.png" /><figcaption>Setting up a SOCKS Proxy Server with Dante on AWS</figcaption></figure><p>A SOCKS proxy server serves various purposes. In this guide, we’ll explore how to set up one using Dante on Amazon Web Services (AWS), particularly useful in scenarios such as running applications on a serverless solution where external services request your service’s static public IP for whitelisting. As serverless solutions limit direct IP provision, employing a SOCKS proxy offers a versatile solution by routing all requests to the external service through the SOCKS server. It’s advisable to assign a public static IP for the SOCKS server in this context. Additionally, we’ll address another common use case: enhancing privacy and security by configuring our SOCKS server to route all requests through the dynamic public IP address assigned to the server instance during creation. For a guide on how to host this on Google Cloud, you can click <a href="https://medium.com/@akintobiidris/setting-up-a-socks-proxy-server-with-dante-on-google-cloud-a76423c52fb4">here</a>.</p><p><strong><em>Requirements</em></strong></p><p><em>To set up a SOCKS proxy server on AWS, you’ll need:</em></p><ul><li><em>An AWS account</em></li><li><em>A security group rule</em></li><li><em>An EC2 instance (virtual machine)</em></li></ul><h4>Security Group Rule Setup</h4><ul><li>Go to the AWS Management Console and navigate to the EC2 Dashboard &gt; Security Groups.</li></ul><figure><img alt="Create Security Group" src="https://cdn-images-1.medium.com/max/1024/1*sHowV1fdobPGWJ5W0gOjhw.png" /><figcaption>Create Security Group</figcaption></figure><ul><li>Click on “Create Security Group.” Name the security group (e.g., ‘allow-sock-1047’) and create a security group description.</li><li>Create security group Inbound Rules: Add a rule to allow incoming traffic on port 22 for ssh and your desired SOCKS port (e.g., port 1047). Apply additional security rules, such as IP restrictions, as needed.</li></ul><figure><img alt="Create security group Inbound Rules" src="https://cdn-images-1.medium.com/max/1024/1*tPghxvuk5BjAHNzuw0IH3A.png" /><figcaption>Create security group Inbound Rules</figcaption></figure><h4>EC2 Instance Setup</h4><ul><li>Navigate to the EC2 Dashboard &gt; Instances.</li><li>Click on “Launch Instance.”</li><li>Name your instance (e.g., ‘sock-server’) and choose an Amazon Linux 2023 (AMI). If you opt for a different image, make sure to update the commands in the script to be compatible with the selected machine image.</li></ul><figure><img alt="Launch instance" src="https://cdn-images-1.medium.com/max/1024/1*fHfpRT4tdzI17yEpOFyM3g.png" /><figcaption>Launch instance</figcaption></figure><ul><li>Choose an appropriate instance type (e.g., t2.micro, which is free-tier eligible).</li><li>Select an existing key pair or create a new one to access your instance securely.</li><li>Click ‘Edit’ in network settings and enable ‘Auto-assign public IP.’</li><li>Click on ‘Select existing security group’ and choose the ‘allow-sock-1047’ rule.</li></ul><figure><img alt="Network setting" src="https://cdn-images-1.medium.com/max/1024/1*5-TtykjZyV8fD1fUEO5wwQ.png" /><figcaption>Network setting</figcaption></figure><ul><li>Click ‘Advanced options’ and paste the script into the ‘User Data’ text area field.</li></ul><figure><img alt="Paste user data script" src="https://cdn-images-1.medium.com/max/1024/1*gkaq90oYSI6atQK8fnEQcQ.png" /><figcaption>Paste user data script</figcaption></figure><ul><li>Review your configurations and click on “Launch.”</li></ul><p><strong><em>script</em></strong></p><pre>#!/bin/bash<br><br># Set terminal type<br>export TERM=xterm-256color<br><br># Variables<br>SOCK_USERNAME=&quot;socksproxy&quot;<br>SOKSPROXY_PASS=&quot;socksproxy&quot;<br>SOCK_PORT=1047<br><br># Function to print stage<br>print_stage() {<br>    local TEXT=&quot;$1&quot;<br>    echo -e &quot;\n\e[32m\e[1m $TEXT \e[0m\e[32m&quot;<br>}<br><br># Update system and install dante-server dependencies<br>print_stage &quot;Updating System and install development tools&quot;<br># use yum to install if you&#39;ve selected machine image earlier than 2023<br>sudo dnf update -y<br>sudo dnf groupinstall &quot;Development Tools&quot; -y<br>sudo dnf install libevent-devel -y<br><br># Download and install dante-server<br>print_stage &quot;Downloading and installing dante-server&quot;<br>curl -O https://www.inet.no/dante/files/dante-1.4.3.tar.gz<br>tar xvzf dante-1.4.3.tar.gz<br>cd dante-1.4.3<br>./configure<br>make &amp;&amp; make install<br><br># Create dante configuration file<br>print_stage &quot;Setting up dante-server&quot;<br>cat &lt;&lt;EOF | tee /etc/sockd.conf<br>logoutput: /var/log/sockd.log<br>internal: 0.0.0.0 port = ${SOCK_PORT}<br>external: enX0<br>clientmethod: none<br>socksmethod: username<br>user.privileged: root<br>user.notprivileged: nobody<br>client pass {<br>    from: 0.0.0.0/0 to: 0.0.0.0/0<br>    log: error connect disconnect<br>}<br>socks pass {<br>    from: 0.0.0.0/0 to: 0.0.0.0/0<br>    log: error connect disconnect<br>}<br>EOF<br><br># Add socksproxy user<br>print_stage &quot;Adding ${SOCK_USERNAME} user&quot;<br>sudo useradd -r -s /bin/false ${SOCK_USERNAME}<br>echo &quot;${SOCK_USERNAME}:${SOKSPROXY_PASS}&quot; | sudo chpasswd<br><br># Start sockd<br>sudo /usr/local/sbin/sockd -D<br><br>print_stage &quot;Installation Completed&quot;<br><br># Get public IP address (metadata version 1)<br># PUBLIC_IPV4=$(curl -s http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address 2&gt;/dev/null || echo &quot;N/A&quot;)<br><br># Get public IP address (metadata version 2 - token required)<br>TOKEN=$(curl -X PUT &quot;http://169.254.169.254/latest/api/token&quot; -H &quot;X-aws-ec2-metadata-token-ttl-seconds: 21600&quot; 2&gt;/dev/null)<br>PUBLIC_IPV4=$(curl -H &quot;X-aws-ec2-metadata-token: $TOKEN&quot; -s http://169.254.169.254/latest/meta-data/public-ipv4 2&gt;/dev/null || echo &quot;N/A&quot;)<br><br># Display configuration details and IP addresses<br>print_stage &quot;Configuration Details:&quot;<br>echo -e &quot;\033[1mIP:\033[0m ${PUBLIC_IPV4}&quot;<br>echo -e &quot;\033[1mUsername:\033[0m ${SOCK_USERNAME}&quot;<br>echo -e &quot;\033[1mPassword:\033[0m ${SOKSPROXY_PASS}&quot;<br>echo -e &quot;\033[1mPort:\033[0m ${SOCK_PORT}&quot;</pre><p><strong><em>Script Explanation</em></strong></p><p>For brevity, we’ll focus on the Dante configuration in the script. For more configuration options you can visit <a href="https://www.inet.no/dante/doc/latest/config/index.html">here</a>. The script uses Dante version 1.4.3 which is the latest at the time of writing this article. Version 1.5 is currently in testing phase and it is set to roll out first quarter of this year.</p><blockquote><strong><em>logoutput: /var/log/sockd.log:</em></strong> Specifies the path for the log file. In this case, it will be stored at /var/log/sockd.log.<br><strong><em>internal: 0.0.0.0 port = ${SOCK_PORT}:</em></strong> Configures the internal IP address and port on which the SOCKS server will listen for incoming connections. The variable ${SOCK_PORT} is used to set the specified port (in this case, 1047).<br><strong><em>external: ens4</em></strong><em>:</em> Defines the external network interface to bind to. In this script, it uses the interface ens4.<br><strong><em>clientmethod: none:</em></strong> Specifies that clients connecting to the SOCKS server do not need to authenticate.<br><strong><em>socksmethod: username:</em></strong> Specifies that the SOCKS server will use username/password authentication for connections.<br><strong><em>user.privileged: root:</em></strong> Sets the privileged user for the SOCKS server to root.<br><strong><em>user.notprivileged: nobody:</em></strong> Sets the non-privileged user for the SOCKS server to nobody.<br><strong><em>client pass { … }:</em></strong> Defines a rule allowing connections from any IP (0.0.0.0/0) to any destination. It logs errors related to connection and disconnection.<br><strong><em>socks pass { … }:</em></strong> Similar to the client pass rule, this allows SOCKS connections from any IP to any destination and logs related errors.</blockquote><p>Once the instance is running, SSH into it to view the script log using cat /var/log/cloud-init-output.log. Please note that the script might take a while to complete due to the compilation of Dante and the use of a small machine type.<br>You can also rerun the startup script from the SSH terminal by using sudo bash /var/lib/cloud/instance/user-data.txt. This could be useful when you edit the instance startup script and need to rerun it manually.</p><h4>Testing the SOCKS Proxy</h4><ul><li>Check if the configured port is open using:</li></ul><pre>nc -zv ${IP} ${PORT}</pre><ul><li>Verify the SOCKS server functionality by curling Google’s home page with the command:</li></ul><pre>socks5://${USERNAME}:${PASS}@${IP}:${PORT} https://www.google.com</pre><h4>SOCKS Usage</h4><ul><li><strong>In browser</strong></li></ul><p>Install the Proxy Toggle Firefox extension and configure it with the SOCKS settings to route browser traffic through the SOCKS server.</p><figure><img alt="Proxy Toggle Firefox extension configuration" src="https://cdn-images-1.medium.com/max/1024/1*lRjVSv6982B787ZSc3-jhQ.png" /><figcaption>Proxy Toggle Firefox extension configuration</figcaption></figure><ul><li><strong>In code</strong><br>Use Axios in JavaScript with the socks-proxy-agent module for making requests through the SOCKS server.</li></ul><pre>import axios from &#39;axios&#39;;<br>import { SocksProxyAgent } from &#39;socks-proxy-agent&#39;;<br><br>// Get socks config from the environment. - Assuming the variables are available<br>const { SOCKS_HOST, SOCKS_PORT, SOCKS_USERNAME, SOCKS_PASSWORD } = process.env;<br><br>// Setup proxy agent<br>const socksV5Agent = new SocksProxyAgent(`socks5://${SOCKS_USERNAME}:${SOCKS_PASSWORD}@${SOCKS_HOST}:${SOCKS_PORT}`);<br><br>// Create socks axios instance<br>const socksClient = axios.create({<br>    httpsAgent: socksV5Agent,<br>    httpAgent: socksV5Agent,<br>});<br><br>// Use the instance <br>(async () =&gt; {<br>    try {<br>        const { data } = await socksClient.get(&#39;https://api.ipify.org&#39;);<br>        console.log(`Our socks IP is ${data}`);<br>    } catch (error) {<br>        console.error(&#39;Error fetching IP:&#39;, error.message);<br>        // Handle the error as needed<br>    }<br>})();</pre><h3>Conclusion</h3><p>In conclusion, this guide has equipped you with the knowledge and step-by-step instructions to seamlessly set up a SOCKS proxy server on AWS using Dante. By following the outlined procedures, you can establish a robust SOCKS proxy server ready to meet your specific needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc4ce6f95bae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a SOCKS Proxy Server with Dante on Google Cloud]]></title>
            <link>https://medium.com/@akintobiidris/setting-up-a-socks-proxy-server-with-dante-on-google-cloud-a76423c52fb4?source=rss-49ea7a7ba30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a76423c52fb4</guid>
            <category><![CDATA[socks]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Idris Akintobi]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 22:15:32 GMT</pubDate>
            <atom:updated>2024-01-11T23:25:19.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Setting up a SOCKS Proxy Server with Dante on Google Cloud" src="https://cdn-images-1.medium.com/max/1024/1*VXOwo9nAqr_ZvFoPpPb16g.png" /><figcaption>Setting up a SOCKS Proxy Server with Dante on Google Cloud</figcaption></figure><p>A SOCKS proxy server can serve various purposes, and in this guide, we’ll explore how to set up one using Dante on Google Cloud. One common use case arises when you’re running your applications on a serverless solution, and external services request your service’s static public IP for whitelisting. Since we know that serverless solutions limit direct IP provision, employing a SOCKS proxy can be a versatile solution. All requests to the external service can be routed through the SOCKS server. It is advisable to assign a public static IP for the SOCKS server in this kind of solution. Another common use case we will consider in this article is enhancing privacy and security. We will be setting up our sock server to route all requests through the dynamic public IP address assigned to the server instance when created. For a guide on how to host this on AWS, you can click <a href="https://medium.com/@akintobiidris/setting-up-a-socks-proxy-server-with-dante-on-aws-dc4ce6f95bae">here</a>.</p><h4><em>Requirements</em></h4><p><em>To set up a SOCKS proxy server, you’ll need:</em></p><ul><li><em>A Google Cloud account</em></li><li><em>A firewall rule</em></li><li><em>A virtual machine (VM) instance</em></li></ul><h3>Firewall Rule Setup</h3><ul><li>Go to the GCloud console, navigate to VPC Network &gt; Firewall.</li><li>Click on “Create Firewall Rule.”</li><li>Name the rule (e.g., ‘allow-sock-1047’) and create a target tag that will be used to tag the VM. In this case, we are using the rule name as the target tag.</li></ul><figure><img alt="Create firewall rule" src="https://cdn-images-1.medium.com/max/1024/1*-DmHfm_2K9v8luaG_pVWSg.png" /><figcaption>Create firewall rule</figcaption></figure><ul><li>Set the rule to allow traffic on your desired port. For this guide, we will be using port 1047. You can apply additional security rules, such as IP restrictions, as needed.</li></ul><figure><img alt="Firewall rule allow port 1047" src="https://cdn-images-1.medium.com/max/1024/1*gflm6b1jtUNJ5T2qvsQ3rQ.png" /><figcaption>Firewall rule allow port 1047</figcaption></figure><h3>VM Instance Setup</h3><ul><li>Navigate to Compute Engine &gt; VM Instances.</li><li>Click on “Create Instance.”</li><li>Name your instance (e.g., ‘sock-server’) and set the location to your preference.</li><li>Choose an appropriate machine type (e.g., e2-micro to reduce costs).</li></ul><figure><img alt="Select e2-micro machine type" src="https://cdn-images-1.medium.com/max/1024/1*69i_pdZfWPWftYer26MQyg.png" /><figcaption>Select e2-micro machine type</figcaption></figure><ul><li>Under Advanced Options and Networking, add the ‘allow-sock-1047’ tag (firewall rule tag)</li></ul><figure><img alt="Add network tag to vm instance." src="https://cdn-images-1.medium.com/max/1024/1*bwRTCrfJJe0TyRo-nZiPQQ.png" /><figcaption>Add network tag to vm instance.</figcaption></figure><ul><li>In the Management section, paste the provided script into the automation text field, then click create.</li></ul><figure><img alt="Paste startup script" src="https://cdn-images-1.medium.com/max/1024/1*mYPZP12lgeuRo_SHc_dQPQ.png" /><figcaption>Paste startup script</figcaption></figure><p><strong><em>Script</em></strong></p><pre>#!/bin/bash<br><br># Set terminal type<br>export TERM=xterm-256color<br><br># Variables - update these<br>SOCK_USERNAME=&quot;socksproxy&quot;<br>SOKSPROXY_PASS=&quot;socksproxy&quot;<br>SOCK_PORT=1047<br><br># Function to print stage<br>print_stage() {<br>    local TEXT=&quot;$1&quot;<br>    echo -e &quot;\n\e[32m\e[1m $TEXT \e[0m\e[32m&quot;<br>}<br><br>print_stage &quot;Updating System and installing dante-server&quot;<br># Install gcc, make, and curl<br>apt-get update<br>apt-get install -y gcc make curl<br><br># Download and install dante-server<br>curl -O https://www.inet.no/dante/files/dante-1.4.3.tar.gz<br>tar xvzf dante-1.4.3.tar.gz<br>cd dante-1.4.3<br>./configure<br>make &amp;&amp; make install<br><br># Create danted configuration file<br>cat &lt;&lt;EOF | tee /etc/sockd.conf<br>logoutput: /var/log/sockd.log<br>internal: 0.0.0.0 port = ${SOCK_PORT}<br>external: ens4<br>clientmethod: none<br>socksmethod: username<br>user.privileged: root<br>user.notprivileged: nobody<br>client pass {<br>    from: 0.0.0.0/0 to: 0.0.0.0/0<br>    log: error connect disconnect<br>}<br>socks pass {<br>    from: 0.0.0.0/0 to: 0.0.0.0/0<br>    log: error connect disconnect<br>}<br>EOF<br><br><br># Add socksproxy user<br>print_stage &quot;Adding ${SOCK_USERNAME} user&quot;<br>useradd -r -s /bin/false ${SOCK_USERNAME}<br>echo &quot;${SOCK_USERNAME}:${SOKSPROXY_PASS}&quot; | chpasswd<br><br># Start sockd<br>/usr/local/sbin/sockd -D<br><br>print_stage &quot;Installation Completed&quot;<br><br># Get public IP address<br>PUBLIC_IPV4=$(curl -s -H &quot;Metadata-Flavor: Google&quot; http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip)<br><br># Display configuration details<br>print_stage &quot;Configuration Details:&quot;<br>echo -e &quot;\033[1mIP:\033[0m ${PUBLIC_IPV4}&quot;<br>echo -e &quot;\033[1mUsername:\033[0m ${SOCK_USERNAME}&quot;<br>echo -e &quot;\033[1mPassword:\033[0m ${SOKSPROXY_PASS}&quot;<br>echo -e &quot;\033[1mPort:\033[0m ${SOCK_PORT}&quot;</pre><p><strong><em>Script Explanation</em></strong></p><p>For brevity, we’ll focus on the Dante configuration in the script. For more configuration options you can visit <a href="https://www.inet.no/dante/doc/latest/config/index.html">here</a><a href="https://www.inet.no/dante/doc/latest/config/index.html.">.</a> The script uses Dante version 1.4.3 which is the latest at the time of writing this article. Version 1.5 is currently in testing phase and it is set to roll out first quarter of this year.</p><blockquote><strong>logoutput: /var/log/sockd.log</strong><em>: Specifies the path for the log file. In this case, it will be stored at /var/log/sockd.log.</em><br><strong>internal: 0.0.0.0 port = ${SOCK_PORT}</strong>:<em> Configures the internal IP address and port on which the SOCKS server will listen for incoming connections. The variable ${SOCK_PORT} is used to set the specified port (in this case, 1047).</em><br><strong>external: ens4</strong>: <em>Defines the external network interface to bind to. In this script, it uses the interface ens4.<br></em><strong>clientmethod: none</strong>: <em>Specifies that clients connecting to the SOCKS server do not need to authenticate.<br></em><strong>socksmethod: username</strong>: <em>Specifies that the SOCKS server will use username/password authentication for connections.<br></em><strong>user.privileged: root</strong>: <em>Sets the privileged user for the SOCKS server to root.<br></em><strong>user.notprivileged: nobody</strong>: <em>Sets the non-privileged user for the SOCKS server to nobody.<br></em><strong>client pass { … }</strong>: <em>Defines a rule allowing connections from any IP (0.0.0.0/0) to any destination. It logs errors related to connection and disconnection.<br></em><strong>socks pass { … }</strong>: <em>Similar to the client pass rule, this allows SOCKS connections from any IP to any destination and logs related errors.</em></blockquote><p>Once the instance is running, SSH into it to view the script log using sudo journalctl -u google-startup-scripts.service. Please note that the script might take a while to complete due to the compilation of Dante and the use of a small machine type.<br>You can also rerun the startup script from the SSH terminal by using sudo google_metadata_script_runner startup. This could be useful when you edit the instance startup script and need to rerun it manually.</p><h4>Testing the SOCKS Proxy</h4><ul><li>Check if the configured port is open using:</li></ul><pre>nc -zv ${IP} ${PORT}</pre><ul><li>Verify the SOCKS server functionality by curling Google’s home page with the command:</li></ul><pre>curl -v -x socks5://${USERNAME}:${PASS}@${IP}:${PORT} https://www.google.com</pre><h4>SOCKS Usage</h4><ul><li><strong>In browser</strong></li></ul><p>Install the Proxy Toggle Firefox extension and configure it with the SOCKS settings to route browser traffic through the SOCKS server.</p><figure><img alt="Firefox Proxy Toggle extension configuration" src="https://cdn-images-1.medium.com/max/1024/1*lRjVSv6982B787ZSc3-jhQ.png" /><figcaption>Firefox Proxy Toggle extension configuration</figcaption></figure><ul><li><strong>In code</strong></li></ul><p>Use Axios in JavaScript with the socks-proxy-agent module for making requests through the SOCKS server.</p><pre>import axios from &#39;axios&#39;;<br>import { SocksProxyAgent } from &#39;socks-proxy-agent&#39;;<br><br>// Get socks config from the environment. - Assuming the variables are available<br>const { SOCKS_HOST, SOCKS_PORT, SOCKS_USERNAME, SOCKS_PASSWORD } = process.env;<br><br><br>// Setup proxy agent<br>const socksV5Agent = new SocksProxyAgent(`socks5://${SOCKS_USERNAME}:${SOCKS_PASSWORD}@${SOCKS_HOST}:${SOCKS_PORT}`);<br><br>// Create socks axios instance<br>const socksClient = axios.create({<br>    httpsAgent: socksV5Agent,<br>    httpAgent: socksV5Agent,<br>});<br><br>// Use the instance <br>(async () =&gt; {<br>    try {<br>        const { data } = await socksClient.get(&#39;https://api.ipify.org&#39;);<br>        console.log(`Our socks IP is ${data}`);<br>    } catch (error) {<br>        console.error(&#39;Error fetching IP:&#39;, error.message);<br>        // Handle the error as needed<br>    }<br>})();<br></pre><h3><strong>Conclusion</strong></h3><p>In conclusion, this guide has equipped you with the knowledge and step-by-step instructions to seamlessly set up a SOCKS proxy server on Google Cloud using Dante. By following the outlined procedures, from firewall rule setup to the execution of the installation script, you can establish a robust SOCKS proxy server ready to meet your specific needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a76423c52fb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caveat of using javascript Date object constructor]]></title>
            <link>https://medium.com/@akintobiidris/caveat-of-using-javascript-date-object-constructor-2d0ce87a4f67?source=rss-49ea7a7ba30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d0ce87a4f67</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Idris Akintobi]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 13:49:22 GMT</pubDate>
            <atom:updated>2023-12-24T13:49:22.413Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hU93vU1Sc4vs_Mj511ENtA.jpeg" /><figcaption>caveat-of-using-javascript-date-object-constructor</figcaption></figure><p><em>JavaScript’s Date object provides powerful tools for working with dates, but it’s important to be mindful of the timezone implications, especially in distributed systems.</em></p><h3>Example Scenarios</h3><p><strong>1. Converting “YYYYMMDDHHMMSS” to Epoch Milliseconds</strong></p><p>Imagine a scenario where an external service provides dates in the format “YYYYMMDDHHMMSS,” and the task is to convert them to Unix timestamps (epoch milliseconds). The following function accomplishes this task:</p><pre>function convertYMDHMSToEpoch(dateString) {<br>    const date = new Date(<br>        +dateString.substring(0, 4),<br>        +dateString.substring(4, 6) - 1,<br>        +dateString.substring(6, 8),<br>        +dateString.substring(8, 10),<br>        +dateString.substring(10, 12),<br>        +dateString.substring(12, 14)<br>    );<br>    return date.getTime().toString();<br>}</pre><p>However, it’s crucial to note that this function may return different values depending on the timezone of the environment where the code is executed.</p><p><strong>2. Converting ISO Date String to User-Friendly Format</strong></p><p>Suppose you receive a date in ISO format, and the goal is to display it in a user-friendly format. The following code accomplishes this using the Date object constructor:</p><pre>const isoString = &#39;2023-01-01T23:00:00Z&#39;;<br>new Date(isoString).toString().substring(0, 24);</pre><p>Again, the issue here is that the output may vary based on the timezone of the runtime environment.</p><h3>Testing with Different Timezones</h3><p>To illustrate the impact of timezones, let’s take the second example and test it with different timezones:</p><pre>const isoString = &#39;2023-01-01T23:00:00Z&#39;;<br><br>process.env.TZ = &#39;UTC-8&#39;;<br>new Date(isoString).toString().substring(0, 24); // Mon Jan 02 2023 07:00:00<br><br>process.env.TZ = &#39;UTC&#39;;<br>new Date(isoString).toString().substring(0, 24); // Sun Jan 01 2023 23:00:00</pre><p>The output will vary based on the runtime environment’s timezone.</p><h3>Best Practices</h3><h4>1. Default to UTC</h4><p>Defaulting backend services to UTC is a widely adopted best practice. You can set the environment variable TZ to ‘UTC’ to enforce this.</p><pre>export TZ=UTC</pre><p>or</p><pre>process.env.TZ = &#39;UTC&#39;</pre><p>We can refactor the function in out first example to enforce UTC timezone with the Date constructor.</p><pre>// Convert &quot;YYYYMMDDHHMMSS&quot; to milliseconds in UTC<br>mapToTimestamp(dateString) {<br>    const date = new Date(<br>        Date.UTC(<br>            +dateString.substring(0, 4),<br>            +dateString.substring(4, 6) - 1,<br>            +dateString.substring(6, 8),<br>            +dateString.substring(8, 10),<br>            +dateString.substring(10, 12),<br>            +dateString.substring(12, 14)<br>        )<br>    );<br>    return date.getTime().toString();<br>}</pre><p>Now, this function will return the same value in different timezones.</p><p>We can then convert to local time on the client side using the toLocaleString method:</p><pre>const date = new Date(&#39;2023-01-01T12:00:00Z&#39;);<br><br>// Display in the system&#39;s timezone<br>const formattedDate = date.toLocaleString(&#39;en-US&#39;);<br><br>// Display in a specific timezone passed in the options (e.g., UTC)<br>const formattedDateUTC = date.toLocaleString(&#39;en-US&#39;, { timeZone: &#39;UTC&#39; });</pre><h4>2. Explore Date Manipulation Libraries</h4><p>Consider using third-party date manipulation libraries like day.js or date-fns. These libraries offer more control over formatting and timezone handling, allowing you to create consistent and customized date displays across different environments.</p><pre>// Example using day.js<br>import dayjs from &#39;dayjs&#39;;<br>import utc from &#39;dayjs/plugin/utc.js&#39;;<br><br>dayjs.extend(utc);<br>process.env.TZ = &#39;America/New_York&#39;;<br><br>console.log(dayjs().utc().format()); // Output in UTC<br>console.log(dayjs().format()); // Output in America/New_York</pre><h3>Conclusion</h3><p>Considering time zones is essential for robust and reliable JavaScript applications. This combination of defaulting backend services to UTC and converting to local time on the client side promotes consistency in date and time handling throughout your application, contributing to a smoother user experience and mitigating potential issues related to timezone disparities. Date manipulation libraries can also be leveraged to ensure consistency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d0ce87a4f67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sendgrid mail service in NestJS]]></title>
            <link>https://medium.com/@akintobiidris/sendgrid-mail-service-in-nestjs-81d797d3bfae?source=rss-49ea7a7ba30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/81d797d3bfae</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[sendgrid]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[email]]></category>
            <dc:creator><![CDATA[Idris Akintobi]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 15:40:38 GMT</pubDate>
            <atom:updated>2023-12-28T09:55:12.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONVf5nT0VSmjjpfQxL8L4A.jpeg" /><figcaption>How to use sendgrid mail service in NestJS</figcaption></figure><p>This article illustrates how to integrate SendGrid mail service into your NestJS application.</p><p><strong>Step 1: Install NestJS CLI</strong><br>Skip to step 3 if you already have an existing NestJS application. Install the NestJS CLI globally using npm:</p><pre>npm install -g @nestjs/cli</pre><p><strong>Step 2: Create a New NestJS Project</strong><br>Use the NestJS CLI to create a new project. Name it whatever you like; for this article, we’ll use “sendgrid-in-nestjs.”</p><pre>nest new sendgrid-in-nestjs<br>cd sendgrid-in-nestjs</pre><p><strong>Step 3: Install SendGrid Package</strong><br>Install the @sendgrid/mail package:</p><pre>npm install @sendgrid/mail</pre><p><strong>Step 4: Set up SendGrid API Key</strong><br>Obtain your SendGrid API key from the SendGrid dashboard and store it in your environment variables or use a configuration service.</p><pre>SENDGRID_API_KEY=your-sendgrid-api-key</pre><p><strong>Step 5: Create Email Module</strong><br>Create an email module that will contain our implementations.</p><pre>nest generate module email</pre><p><strong>Step 6: Create SendGrid Client class</strong><br>Create SendGridClient class in sendgrid-client.ts inside the email folder, which will use the API key from the configuration to interact with the SendGrid API using the @sendgrid/mail package:</p><pre>nest generate class email/sendgrid-client --flat --no-spec</pre><p><strong>Step 7: Update SendGrid Client</strong><br>Update sendgrid-client.ts to use the API key from the configuration:</p><pre>// src/email/sendgrid-client.ts<br><br>import { Injectable, Logger } from &#39;@nestjs/common&#39;;<br>import { MailDataRequired, default as SendGrid } from &#39;@sendgrid/mail&#39;;<br><br>@Injectable()<br>export class SendGridClient {<br>  private logger: Logger;<br>  constructor() {<br>    //Initialize the logger. This is done for simplicity. You can use a logger service instead<br>    this.logger = new Logger(SendGridClient.name);<br>    //Get the API key from config service or environment variable<br>    SendGrid.setApiKey(process.env.SENDGRID_API_KEY);<br>  }<br><br>  async send(mail: MailDataRequired): Promise&lt;void&gt; {<br>    try {<br>      await SendGrid.send(mail);<br>      this.logger.log(`Email successfully dispatched to ${mail.to as string}`);<br>    } catch (error) {<br>      //You can do more with the error<br>      this.logger.error(&#39;Error while sending email&#39;, error);<br>      throw error;<br>    }<br>  }<br>}<br><br>//NOTE You have to set &quot;esModuleInterop&quot; to true in your tsconfig file to be able to use the default key in import.</pre><p><strong>Step 8: Create Email Service</strong><br>Create email.service.ts file. It will abstract the SendGridClient, so that we can have different method for specific email use case.</p><pre>nest generate service email/email --flat --no-spec</pre><p><strong>Step 9: Update Email Service</strong><br>Our email service class will consist of 2 methods: “sendTestEmail” and “sendEmailWithTemplate”. The former will be a method to send a test email and the latter will be a method to send email with a preconfigured sendgrid email template. The template ID will be retrieved from the Sendgrid dashboard:dynamic template.</p><pre>// src/email/email.service.ts<br><br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { MailDataRequired } from &#39;@sendgrid/mail&#39;;<br>import { SendGridClient } from &#39;./sendgrid-client&#39;;<br><br>@Injectable()<br>export class EmailService {<br>  constructor(private readonly sendGridClient: SendGridClient) {}<br><br>  async sendTestEmail(recipient: string, body = &#39;This is a test mail&#39;): Promise&lt;void&gt; {<br>    const mail: MailDataRequired = {<br>      to: recipient,<br>      from: &#39;noreply@domain.com&#39;, //Approved sender ID in Sendgrid<br>      subject: &#39;Test email&#39;,<br>      content: [{ type: &#39;text/plain&#39;, value: body }],<br>    };<br>    await this.sendGridClient.send(mail);<br>  }<br><br>  async sendEmailWithTemplate(recipient: string, body: string): Promise&lt;void&gt; {<br>    const mail: MailDataRequired = {<br>      to: recipient,<br>      cc: &#39;example@mail.com&#39;, //Assuming you want to send a copy to this email<br>      from: &#39;noreply@domain.com&#39;, //Approved sender ID in Sendgrid<br>      templateId: &#39;Sendgrid_template_ID&#39;, //Retrieve from config service or environment variable<br>      dynamicTemplateData: { body, subject: &#39;Send Email with template&#39; }, //The data to be used in the template<br>    };<br>    await this.sendGridClient.send(mail);<br>  }<br>}</pre><p><strong>Step 10: Update Email Module</strong><br>Update the email module by adding the SendGridClient class as a provider and exporting the email service so that it is accessible to any module that imports the Email module.</p><pre>// src/email/email.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { EmailService } from &#39;./email.service&#39;;<br>import { SendGridClient } from &#39;./sendgrid-client&#39;;<br><br>@Module({<br>  providers: [EmailService, SendGridClient],<br>  exports: [EmailService],<br>})<br>export class EmailModule {}</pre><p><strong>Step 11: Use Email Service in Controller</strong><br>Import the email service and make it available in the appropriate controller. We will be using the app controller. Update the app.controller.ts file to provide an endpoint to test the email service.</p><pre>// src/app.controller.ts<br><br>import { Body, Controller, Get, Post } from &#39;@nestjs/common&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { EmailService } from &#39;./email/email.service&#39;;<br><br>@Controller()<br>export class AppController {<br>  constructor(<br>    private readonly appService: AppService,<br>    private readonly emailService: EmailService,<br>  ) {}<br><br>  @Get()<br>  getHello(): string {<br>    return this.appService.getHello();<br>  }<br><br>  @Post(&#39;send-test-email&#39;)<br>  async sendEmail(<br>    @Body() sendEmailDTO: { recipient: string; body: string },<br>  ): Promise&lt;void&gt; {<br>    await this.emailService.sendTestEmail(<br>      sendEmailDTO.recipient,<br>      sendEmailDTO.body,<br>    );<br>  }<br>}</pre><p><strong>Step 12: Run Your NestJS Application</strong><br>Run your NestJS application:</p><pre>npm run start:dev</pre><p>Make a POST request to <a href="http://localhost:3000/send-test-email">http://localhost:3000/send-test-email</a> using an API testing tool such as Postman. Include the recipient email and optional body parameters in the request body as JSON payload.</p><p>Remember to replace placeholders like ‘Sendgrid_template_ID’, ‘SENDGRID_API_KEY’, etc., with your actual values.</p><p><strong>Conclusion</strong><br>In summary, this guide has demonstrated the straightforward integration of SendGrid mail service into your NestJS application. By following the provided steps, you’ve set up the project, configured the SendGrid API key, and created essential modules and classes. With a modular structure and clear instructions, you now have a solid foundation for incorporating efficient email functionality into your NestJS projects. For any questions or issues, don’t hesitate to ask. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81d797d3bfae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Redis Client in NestJS]]></title>
            <link>https://medium.com/@akintobiidris/using-redis-client-in-nestjs-3fe80eb91a49?source=rss-49ea7a7ba30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fe80eb91a49</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Idris Akintobi]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 18:33:40 GMT</pubDate>
            <atom:updated>2023-09-27T18:33:40.835Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*YP-5f3VUJ_J7h_ccXQ98CA.png" /><figcaption>Using redis client with nestjs</figcaption></figure><p>In this article, we will explore how to set up a Redis client in a NestJS application for caching and storing short-lived data. We will provide code snippets and explanations for each step of the process.</p><h4>Setting Up the Nestjs Project</h4><p>First, we need to install the Nest CLI by running the following command in your terminal:</p><pre>npm install -g @nestjs/cli</pre><p>Next, create a new NestJS project using the following command, replacing `&lt;your-project-name&gt;` with your desired project name:</p><pre>nest new &lt;your-project-name&gt;</pre><p>This project will focus on two primary uses of Redis: caching and storing short-lived data. We’ll use Node.js version 18 and the <em>ioredis</em> library to connect to the Redis service.</p><h4>Setting Up the Redis Client Factory</h4><p>To interact with Redis, we need to set up a Redis client factory that will create a Redis connection instance used throughout the code. Here’s an example of the Redis client factory.</p><pre>import { FactoryProvider } from &#39;@nestjs/common&#39;;<br>import { Redis } from &#39;ioredis&#39;;<br><br>export const redisClientFactory: FactoryProvider&lt;Redis&gt; = {<br>    provide: &#39;RedisClient&#39;,<br>    useFactory: () =&gt; {<br>        const redisInstance = new Redis({<br>            host: process.env.REDIS_HOST,<br>            port: +process.env.REDIS_PORT,<br>        });<br><br>        redisInstance.on(&#39;error&#39;, e =&gt; {<br>            throw new Error(`Redis connection failed: ${e}`);<br>        });<br><br>        return redisInstance;<br>    },<br>    inject: [],<br>};</pre><p>Please note that in this example, we are not implementing any connection retry mechanism. An error will be thrown if there’s an issue with the Redis connection, which may not be the best practice but suits our use case here.</p><h4>Setting Up the Redis Repository</h4><p>We will set up a Redis repository to abstract our Redis client and provide methods for interacting with the Redis store in the application layer. Here’s an example of the Redis repository.</p><pre>import { Inject, Injectable, OnModuleDestroy } from &#39;@nestjs/common&#39;;<br>import { Redis } from &#39;ioredis&#39;;<br><br>import { RedisRepositoryInterface } from &#39;../../../domain/interface/redis.repository.interface&#39;;<br><br>@Injectable()<br>export class RedisRepository implements OnModuleDestroy, RedisRepositoryInterface {<br>    constructor(@Inject(&#39;RedisClient&#39;) private readonly redisClient: Redis) {}<br><br>    onModuleDestroy(): void {<br>        this.redisClient.disconnect();<br>    }<br><br>    async get(prefix: string, key: string): Promise&lt;string | null&gt; {<br>        return this.redisClient.get(`${prefix}:${key}`);<br>    }<br><br>    async set(prefix: string, key: string, value: string): Promise&lt;void&gt; {<br>        await this.redisClient.set(`${prefix}:${key}`, value);<br>    }<br><br>    async delete(prefix: string, key: string): Promise&lt;void&gt; {<br>        await this.redisClient.del(`${prefix}:${key}`);<br>    }<br><br>    async setWithExpiry(prefix: string, key: string, value: string, expiry: number): Promise&lt;void&gt; {<br>        await this.redisClient.set(`${prefix}:${key}`, value, &#39;EX&#39;, expiry);<br>    }<br>}</pre><p>We use the NestJS <em>onModuleDestroy</em> lifecycle event method to close the Redis connection when the application is torn down. This event is triggered when <em>app.close()</em> is called or when the process receives a special system signal, such as <em>SIGTERM</em>, if <em>enableShutdownHooks</em> is called during application bootstrap.</p><p>As you can see, we use a prefix for all keys stored in Redis. This allows us to create a folder-like structure when accessing the Redis store with applications like RedisInsight, using the colon (‘:’) as the delimiter. The prefix is defined as an enum value containing all the data stores (collections/tables) used in the project.</p><h4>Setting Up the Redis Service</h4><p>Finally, we create a Redis service to be used in the application layer. The Redis service encapsulates the Redis repository and provides the methods needed in the application layer. Here’s an example of the Redis service.</p><pre>import { Inject, Injectable } from &#39;@nestjs/common&#39;;<br><br>import { RedisPrefixEnum } from &#39;../domain/enum/redis-prefix-enum&#39;;<br>import { ProductInterface } from &#39;../domain/interface/product.interface&#39;;<br>import { RedisRepository } from &#39;../infrastructure/redis/repository/redis.repository&#39;;<br><br>const oneDayInSeconds = 60 * 60 * 24;<br>const tenMinutesInSeconds = 60 * 10;<br><br>@Injectable()<br>export class RedisService {<br>    constructor(@Inject(RedisRepository) private readonly redisRepository: RedisRepository) {}<br><br>    async saveProduct(productId: string, productData: ProductInterface): Promise&lt;void&gt; {<br>        // Expiry is set to 1 day<br>        await this.redisRepository.setWithExpiry(<br>            RedisPrefixEnum.PRODUCT,<br>            productId,<br>            JSON.stringify(productData),<br>            oneDayInSeconds,<br>        );<br>    }<br><br>    async getProduct(productId: string): Promise&lt;ProductInterface | null&gt; {<br>        const product = await this.redisRepository.get(RedisPrefixEnum.PRODUCT, productId);<br>        return JSON.parse(product);<br>    }<br><br>    async saveResetToken(userId: string, token: string): Promise&lt;void&gt; {<br>        // Expiry is set to 10 minutes<br>        await this.redisRepository.setWithExpiry(<br>            RedisPrefixEnum.RESET_TOKEN,<br>            token,<br>            userId,<br>            tenMinutesInSeconds,<br>        );<br>    }<br><br>    async getResetToken(token: string): Promise&lt;string | null&gt; {<br>        return await this.redisRepository.get(RedisPrefixEnum.RESET_TOKEN, token);<br>    }<br>}</pre><p>In this service, we use the <em>RedisPrefixEnum</em> as the collection/table name. We have implemented four methods: `saveProduct` to cache a product for a day, <em>saveResetToken</em> to store a reset token for ten minutes, and <em>getProduct</em> and <em>getResetToken</em> to retrieve stored product and token values, respectively.</p><h4>Using Redis Service in Other Services</h4><p>Now, let’s see how we can use the Redis service in our password reset service and product service.</p><p><strong>Password Reset Service</strong></p><p>Here’s an example of the password reset service using the Redis service.</p><pre>import { Inject, Injectable } from &#39;@nestjs/common&#39;;<br>import { ResetTokenInterface } from &#39;../domain/interface/reset.token.interface&#39;;<br>import { RedisService } from &#39;./redis.service&#39;;<br><br>@Injectable()<br>export class PasswordResetService {<br>    constructor(@Inject(RedisService) private readonly redisService: RedisService) {}<br><br>    async generateResetToken(userId: string): Promise&lt;ResetTokenInterface&gt; {<br>        //NOTE Check if the user exists in the database<br>        //Generate a random number token with the length of 6<br>        const token = Math.floor(100000 + Math.random() * 900000).toString();<br>        await this.redisService.saveResetToken(userId, token);<br>        return { token };<br>    }<br><br>    async getTokenUserId(token: string): Promise&lt;string | null&gt; {<br>        return await this.redisService.getResetToken(token);<br>    }<br>}</pre><p><strong>Product Service</strong></p><p>Here’s an example of the product service using the Redis service.</p><pre>import { Inject, Injectable, InternalServerErrorException } from &#39;@nestjs/common&#39;;<br>import { ProductInterface } from &#39;../domain/interface/product.interface&#39;;<br>import { RedisService } from &#39;./redis.service&#39;;<br><br>// We will be using dummyjson product API to fetch our products data:<br>// This could be any API call or database operations<br>const productURL = &#39;https://dummyjson.com/products/&#39;;<br><br>@Injectable()<br>export class ProductService {<br>    constructor(@Inject(RedisService) private readonly redisService: RedisService) {}<br><br>    async getProduct(productId: string): Promise&lt;any&gt; {<br>        // Check if the product exists in Redis<br>        const product = await this.redisService.getProduct(productId);<br>        if (product) {<br>            console.log(&#39;Cache hit!: Product found in Redis&#39;);<br>            return { data: product };<br>        }<br><br>        const res = await fetch(`${productURL}${productId}`);<br><br>        if (res.ok) {<br>            const product: ProductInterface = await res.json();<br>            // Cache the data in Redis<br>            await this.redisService.saveProduct(`${product.id}`, product);<br>            console.log(&#39;Cache miss!: Product not found in Redis&#39;);<br>            return product;<br>        } else {<br>            throw new InternalServerErrorException(&#39;Something went wrong&#39;);<br>        }<br>    }<br>}</pre><p>These services can be injected into other services or controllers. To keep this article concise, we have not included the controller code, but you can find it in the <a href="https://github.com/IdrisAkintobi/nestjs-with-redis.git">code repository</a>.</p><h4>Conclusion</h4><p>In this article, we explored how to set up a Redis client in a NestJS application for caching and storing short-lived data. We created a Redis client factory, a Redis repository, and a Redis service to abstract the Redis interactions in the application layer. We also demonstrated how to use the Redis service in password reset and product services to enhance data retrieval and caching. By implementing the techniques and structures outlined in this article, you can seamlessly incorporate Redis into your own application, optimizing its performance and enhancing data management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fe80eb91a49" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>