<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Goodness Chukwudi</title>
    <description>The latest articles on DEV Community by Goodness Chukwudi (@goodness-chukwudi).</description>
    <link>https://dev.to/goodness-chukwudi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1437594%2F7b420280-21ef-465c-9407-2b98de1d765d.jpg</url>
      <title>DEV Community: Goodness Chukwudi</title>
      <link>https://dev.to/goodness-chukwudi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/goodness-chukwudi"/>
    <language>en</language>
    <item>
      <title>How To Integrate Gmail API In Your Node.js Application</title>
      <dc:creator>Goodness Chukwudi</dc:creator>
      <pubDate>Sat, 01 Jun 2024 17:02:12 +0000</pubDate>
      <link>https://dev.to/goodness-chukwudi/how-to-integrate-gmail-api-in-your-nodejs-application-5bjl</link>
      <guid>https://dev.to/goodness-chukwudi/how-to-integrate-gmail-api-in-your-nodejs-application-5bjl</guid>
      <description>&lt;p&gt;The Gmail API provides a powerful and flexible solution for integrating Gmail's robust features into your app. With it, you can enable users to read, send, and organise their emails, manage drafts, labels and much more. This guide will walk you through the steps to seamlessly integrate the Gmail API, transforming your application into a centralised hub for email management.&lt;/p&gt;

&lt;p&gt;Whether you’re developing a productivity tool, a customer relationship management (CRM) system, or any application that benefits from streamlined email interactions, this guide will equip you with the necessary knowledge and tools. We'll cover everything from setting up API access and handling authentication to implementing core email functionalities.&lt;/p&gt;

&lt;p&gt;A more robust implementation of a Gmail client using Gmail APIs can be found here &lt;a href="https://github.com/Goodness-Chukwudi/gmail-client" rel="noopener noreferrer"&gt;github.com/Goodness-Chukwudi/gmail-client&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Setting Up Your Gmail Project On Google Cloud Console&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Create a project&lt;/strong&gt;. To create and set up your project on Google cloud console, head over to &lt;a href="https://console.cloud.google.com" rel="noopener noreferrer"&gt;console.cloud.google.com&lt;/a&gt; and sign in with your gmail account. From the project dropdown at the top left corner, create a new project or select an existing project if you have any.&lt;/p&gt;

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

&lt;p&gt;After creating a project, select &lt;code&gt;APIs and services&lt;/code&gt; from the navigation menu at the top left corner.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Enable Gmail APIs&lt;/strong&gt;. Click on &lt;code&gt;+ ENABLE APIS AND SERVICES&lt;/code&gt; at the top of the page. This opens the API library page. Search for &lt;code&gt;Gmail API&lt;/code&gt; select it and click on &lt;code&gt;Enable&lt;/code&gt; to activate Gmail API.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Generate credentials for your app&lt;/strong&gt;. To create the credentials you will use to connect from your app, click on &lt;code&gt;Credentials&lt;/code&gt; in the sidebar under &lt;code&gt;APIs and services&lt;/code&gt; and click on &lt;code&gt;+ CREATE CREDENTIALS&lt;/code&gt; at the top of the screen. Select &lt;code&gt;OAuth Client ID&lt;/code&gt;, select &lt;code&gt;Web application&lt;/code&gt; as application type and click &lt;code&gt;Create&lt;/code&gt;. Copy the &lt;code&gt;Client ID&lt;/code&gt; and &lt;code&gt;Client secret&lt;/code&gt;; You will need it to connect to your Google project from your Node.js app.&lt;/p&gt;

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

&lt;p&gt;&lt;strong&gt;4. OAuth screen Setup&lt;/strong&gt;.  You will be using OAuth to give your app access to a user’s mailbox. Select &lt;code&gt;OAuth consent screen&lt;/code&gt; under &lt;code&gt;Credentials&lt;/code&gt; and fill the name of the app, support email and other details. Don’t bother setting up the scopes, you will do that from your application. Once this is done, you will head to your system to write some code&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Code Setup and API Integrations&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;This tutorial is meant for people with prior knowledge of Node.js already. Consequently, it guide does not cover installation and setup of a Node.js app.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Project setup and dependency installation&lt;/strong&gt;. After setting up your Node.js project, on your terminal run &lt;code&gt;npm i googleapis&lt;/code&gt; to install googleapis from npm. Add the credentials you created to your &lt;code&gt;.env&lt;/code&gt; file: &lt;code&gt;GOOGLE_CLIENT_ID&lt;/code&gt;,  &lt;code&gt;GOOGLE_CLIENT_SECRET&lt;/code&gt;, &lt;code&gt;GMAIL_REDIRECT_URL&lt;/code&gt;(during OAuth authentication, google will call this endpoint with the authentication code if successful). The redirect url needs to be a live url on your server's domain, but you can use &lt;a href="https://ngrok.com" rel="noopener noreferrer"&gt;ngrok&lt;/a&gt; to expose your localhost to the internet to enable us to get the redirect during OAuth authentication. Head over to &lt;a href="https://ngrok.com" rel="noopener noreferrer"&gt;ngrok.com&lt;/a&gt; and follow the instructions there to set up ngrok locally. Once you have set up ngrok, the redirect url should be in this format &lt;code&gt;&amp;lt;your-ngrok-ur/a-route-of-your-choice&amp;gt;&lt;/code&gt;. Eg. &lt;a href="https://my-url/call_back_path" rel="noopener noreferrer"&gt;https://my-url/call_back_path&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. OAuth authentication&lt;/strong&gt;. Create a file, say &lt;code&gt;gmail_service.js&lt;/code&gt; for your Gmail API calls code. Import googleapis and initialise OAuth2 and Gmail client from googleapis. We will use nodemailer’s MailComposer to compose a MIME message for our emails. So go ahead and install nodemailer from npm: &lt;code&gt;npm i nodemailer&lt;/code&gt;. You will be needing it later.&lt;/p&gt;

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

import { google } from "googleapis";
const MailComposer = require("nodemailer/lib/mail-composer");

const oauth2Client = new google.auth.OAuth2(
  process.env.GOOGLE_CLIENT_ID,
  process.env.GOOGLE_CLIENT_SECRET,
  process.env.GMAIL_REDIRECT_URL
);

google.options({auth: oauth2Client})
const gmailClient = google.gmail('v1');


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

&lt;/div&gt;

&lt;p&gt;Setting the auth on the Gmail client with the OAuth client authenticates our app's request to our Google project.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Generate the consent page url&lt;/strong&gt; using the OAuth2 client and open it on a browser to give access to the app. In a real world scenario, this url is returned to the front end part of your app. This enables the user to grant your app access to their email.&lt;/p&gt;

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

const scopes = [
    "https://www.googleapis.com/auth/gmail.labels",
    "https://www.googleapis.com/auth/gmail.modify",
  ];
  const url = oauth2Client.generateAuthUrl({
    access_type: "offline",
    scope: scopes,
    prompt: "consent"
});
console.log(url)


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

&lt;/div&gt;

&lt;p&gt;The scopes specifies the type of access and access level the app will request from the user. Refer to &lt;a href="https://developers.google.com/gmail/api/auth/scopes" rel="noopener noreferrer"&gt;developers.google.com/gmail/api/auth/scopes&lt;/a&gt; for more on scopes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Extract refresh token from auth code&lt;/strong&gt;. You need to specify a route that matches the redirect url you specified in your application. This route must be a GET endpoint. Once the OAuth authentication is complete, Google will call your redirect url with the auth code in the request query. Extract the credentials from the returned code using the OAuth client. The extracted token is an object containing the refresh token among other fields. This refresh token should be saved in a secured place, preferably on your DB. This refresh token is sent alongside and validates every request to the API for this user.&lt;/p&gt;

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

import { Router } from "express";

const router = Router();
router.get("[path]", async (req, res) =&amp;gt; {
    const code = req.query.code as string;
    const {tokens} = await oauth2Client.getToken(code)
    oauth2Client.setCredentials(tokens);
    console.log("refresh_token =========&amp;gt;  ", tokens.refresh_token);
})



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

&lt;/div&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Accessing Gmail APIs&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Now that your Gmail client is set up and authenticated, you can now call Gmail’s API to manage an email's inbox, send email and much more. Go to &lt;a href="https://developers.google.com/gmail/api/guides" rel="noopener noreferrer"&gt;developers.google.com/gmail/api/guides&lt;/a&gt; to see all available APIs and their usages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Retrieving messages&lt;/strong&gt;. The list method retrieves messages in the provided mailbox. &lt;code&gt;me&lt;/code&gt; refers to the email of the user attached to the refresh token of a request. You can replace &lt;code&gt;me&lt;/code&gt; with the actual email address.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

function retrieveMessages() {
  const messagesResponse = await gmailClient.users.messages.list({userId: 'me'});
  const messages = messagesResponse.data.messages;
  console.log("messages =========&amp;gt;  ", messages);
}

await retrieveMessages();


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;2. Get one message.&lt;/strong&gt;&lt;/p&gt;

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

function getOneMessage(messageId) {
  const messageResponse = await gmailClient.users.messages.get({userId: 'me', id: messageId});
  const message = messageResponse.data;

  let messageBody = "";
  const body = message.payload?.parts ? message.payload.parts[1].body : message.payload?.body;

  if (body?.data) {
    const buffer = Buffer.from(body.data, "base64");
    messageBody = buffer.toString("utf-8");
  } 

  //For messages with attachments
  if (body?.attachmentId) {
    const textPart = message.payload?.parts[0]?.parts[1]?.body?.data;
    if (textPart) {
      const buffer = Buffer.from(textPart, "base64");
      messageBody = buffer.toString("utf-8");
    }
  }

  console.log("message =========&amp;gt;  ", messageBody);
}

await getOneMessage(messageId);


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;3. List drafts&lt;/strong&gt;. The list method lists the drafts in the provided mailbox.&lt;/p&gt;

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

function listDrafts() {
  const draftsResponse = await gmailClient.users.drafts.list({userId: 'me'});
  const drafts = draftsResponse.data.drafts;
  console.log("drafts =========&amp;gt;  ", drafts);
}

await listDrafts();


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;4. Get one draft&lt;/strong&gt;&lt;/p&gt;

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

function getOneDraft(draftId) {
  const draftResponse = await gmailClient.users.drafts.get({userId: 'me', id: draftId});
  const draft = draftResponse.data;
  const payload = draft.message?.payload;

  let messageBody = "";
  const body = payload?.parts ? payload.parts[1].body : payload?.body;

  if (body?.data) {
    const buffer = Buffer.from(body.data, "base64");
    messageBody = buffer.toString("utf-8");
  } 

  //For drafts with attachments
  if (body?.attachmentId) {
    //@ts-ignore
    const textPart = payload?.parts[0]?.parts[1]?.body?.data;
    if (textPart) {
      const buffer = Buffer.from(textPart, "base64");
      messageBody = buffer.toString("utf-8");
    }
  }
  console.log("draft =========&amp;gt;  ", messageBody); 
}

await getOneDraft(draftId);


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;5. List labels&lt;/strong&gt;.&lt;/p&gt;

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

function listLabels() {
  const labelsResponse = await gmailClient.users.labels.list({userId: 'me'});
  const labels = labelsResponse.data.labels;
  console.log("labels =========&amp;gt;  ", labels);
}

await listLabels();


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;6. Delete a message&lt;/strong&gt;. A message is deleted by adding a &lt;code&gt;TRASH&lt;/code&gt; label to it. Go to &lt;a href="https://developers.google.com/gmail/api/guides/labels" rel="noopener noreferrer"&gt;developers.google.com/gmail/api/guides/labels&lt;/a&gt; for more on message labels.&lt;/p&gt;

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

function deleteMessage(messageId) {
  await gmailClient.users.messages.trash({userId: 'me', id: messageId});
}

await deleteMessage(messageId);


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;7. Batch delete messages&lt;/strong&gt;. To delete multiple messages at a go, add &lt;code&gt;TRASH&lt;/code&gt; to the label of each message.&lt;/p&gt;

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

function deleteMessages(messageIds) {
  const requestBody = {ids: messageIds, addLabelIds: ["TRASH"]};
  await gmailClient.users.messages.batchModify({userId: 'me', requestBody});
}

await deleteMessages(messageIds);


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;8. Restore a deleted message&lt;/strong&gt;.&lt;/p&gt;

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

function restoreMessage(messageId) {
  await gmailClient.users.messages.untrash({userId: 'me', id: messageId});
}

await restoreMessage(messageId);


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;9. Send mail&lt;/strong&gt;. The email API accepts only MIME email messages that's compliant with &lt;a href="https://datatracker.ietf.org/doc/html/rfc2822" rel="noopener noreferrer"&gt;RFC 2822&lt;/a&gt; and encoded as a base64 string.&lt;/p&gt;

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

function encodeEmail(email) {
  const mail = new MailComposer({
      from: "me",
      to: email.recipient,
      cc: email.cc,
      html: email.body,
      subject: email.subject,
      textEncoding: "base64"
    });

    mail.compile().build((err, message) =&amp;gt; {
      if (err) console.log(err);
      const encodedEmail = Buffer
        .from(message)
        .toString('base64')
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, '');

      return encodedEmail;
    });
}

function sendMessage(emailObject) {
  const requestBody = {
      raw: await encodeEmail(emailObject)
  }
  await gmailClient.users.messages.send({userId: "me", requestBody});
}

await sendMessage(emailObject);


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;10. Create drafts&lt;/strong&gt;. Drafts represent an unsent message with the &lt;code&gt;DRAFT&lt;/code&gt; label applied. The input will be the same with send email API inputs.&lt;/p&gt;

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

function createDraft(emailObject) {
  const requestBody = {
    raw: await encodeEmail()
  }

  await gmailClient.users.drafts.create({userId: 'me', requestBody});
}

await createDraft(emailObject);


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;11. Update drafts&lt;/strong&gt;. Messages do not actually get updated. The update request instead, destroys the message attached to the draft you want to update and replaces it with a new message containing the new MIME message you sent.&lt;/p&gt;

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

function updateDraft(emailObject, draftId) {
  const requestBody = {
    raw: await encodeEmail()
  }

  await gmailClient.users.drafts.update({userId: 'me', id: draftId, requestBody});
}

await updateDraft(emailObject, draftId);


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;12. Delete drafts&lt;/strong&gt;.&lt;/p&gt;

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

function deleteDraft(draftId) {
  await gmailClient.users.drafts.delete({userId: 'me', id: draftId});
}

await deleteDraft(draftId);


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;13. Send drafts&lt;/strong&gt;.&lt;/p&gt;

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

function sendDraft(draftId) {
  const requestBody = {
    id: draftId
  }
  await gmailClient.users.drafts.send({userId: 'me', requestBody});
}

await sendDraft(draftId);


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

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;14. Revoke access&lt;/strong&gt;. Though users can revoke access given to your application from their Gmail app, you can also give them a way to revoke the access from within your application using the &lt;code&gt;revokeToken&lt;/code&gt; API.&lt;/p&gt;


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

&lt;p&gt;function revokeAppAccess(refreshToken) {&lt;br&gt;
  await oauth2Client.revokeToken(refreshToken);&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;await revokeAppAccess(refreshToken);&lt;/p&gt;

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

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  &lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;A full list and implementation guide for all the features available on the Gmail API is available on &lt;a href="https://developers.google.com/gmail/api/guides" rel="noopener noreferrer"&gt;developers.google.com/gmail/api/guides&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;What’s Next?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;A more robust implementation of a Gmail client app, with user authentication management using Node.js and Express.js and MongoDB is available on &lt;a href="https://github.com/Goodness-Chukwudi/gmail-client" rel="noopener noreferrer"&gt;github.com/Goodness-Chukwudi/gmail-client&lt;/a&gt;. Please leave a star on the repo if you find it helpful. Also feel free to raise a PR if you want to contribute more features or improve existing ones. Suggestions are welcomed as well. Reach me on &lt;a href="//mailto:ibechechukwudi@gmail.com"&gt;ibechechukwudi@gmail.com&lt;/a&gt;&lt;/p&gt;

</description>
      <category>gmail</category>
      <category>gmailclient</category>
      <category>gmailapi</category>
      <category>node</category>
    </item>
    <item>
      <title>A step-by-step guide on how to create and publish an npm package</title>
      <dc:creator>Goodness Chukwudi</dc:creator>
      <pubDate>Sat, 20 Apr 2024 05:26:47 +0000</pubDate>
      <link>https://dev.to/goodness-chukwudi/a-step-by-step-guide-on-how-to-create-and-publish-and-npm-package-4ae5</link>
      <guid>https://dev.to/goodness-chukwudi/a-step-by-step-guide-on-how-to-create-and-publish-and-npm-package-4ae5</guid>
      <description>&lt;p&gt;If you are reading this, you are most likely either trying to publish a package to npm or just learning how to publish npm packages. No matter which one you fall into, I’m here to guide you through the steps to achieving that.&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;NPM (Node Package Manager) is the world’s largest software registry. Open source developers from every continent use npm to share and borrow packages, and many organisations use npm to manage private development as well.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you are a javascript developer, chances are that you are familiar with npm.&lt;br&gt;
The scope of this article is publishing a package to npm and I will try to stick to that as much as possible. To seamlessly follow the steps outlined in this article and have a good understanding of the concepts used, you need to be familiar with &lt;em&gt;&lt;strong&gt;javascript&lt;/strong&gt;&lt;/em&gt;, &lt;em&gt;&lt;strong&gt;node&lt;/strong&gt;&lt;/em&gt;, &lt;em&gt;&lt;strong&gt;git&lt;/strong&gt;&lt;/em&gt; and &lt;em&gt;&lt;strong&gt;npm&lt;/strong&gt;&lt;/em&gt;. If you don’t have node installed, head over to the official &lt;a href="https://nodejs.org/en/download/"&gt;website&lt;/a&gt; to download and install Node.js.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 1: Choose a name for your package.
&lt;/h2&gt;

&lt;p&gt;To begin, you will need to choose a name for your package.&lt;br&gt;
Note: Your package name must be unique. Using the exact or similar name of an existing package will return an error when publishing the package to npm. To ensure the uniquenesses of your package name, head over to &lt;a href="https://npmjs.com"&gt;npmjs.com&lt;/a&gt; and search for any existing packages with a similar name.&lt;br&gt;
&lt;strong&gt;If there’s an exact match or a similar name, consider changing the name you will use for your package or publish your package as a scoped package. see “&lt;a href="https://docs.npmjs.com/about-scopes"&gt;about scopes&lt;/a&gt;” for details.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The npm package we will be building for this article will be called &lt;a href="https://www.npmjs.com/package/boolean-converter"&gt;&lt;code&gt;boolean-converter&lt;/code&gt;&lt;/a&gt;, and aims to simplify the process of converting values to boolean in Node.js applications.&lt;br&gt;
As developers working with Node.js, we often encounter scenarios where we need to interpret user input, API responses, or configuration values as boolean values. However, JavaScript's loose typing system can sometimes lead to unexpected results when dealing with truthy and falsy values.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 2: Create a project folder and make it a git repository.
&lt;/h2&gt;

&lt;p&gt;Initialise git in your project folder. I will be using git and github (you can use a service of your choice) for version control. After creating a repository on github, in your computer’s terminal, navigate to the location you want to keep your project and clone the repository you just created using the command &lt;code&gt;git clone &amp;lt;url of repository&amp;gt;&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git clone https://github.com/Goodness-Chukwudi/boolean-converter.git
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 3: Initialise NPM in your project.
&lt;/h2&gt;

&lt;p&gt;From your terminal, navigate to the root of your project folder and initialise npm using the command below 👇&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;p&gt;You can initialise a scoped package by passing the scope flag to the command.&lt;/p&gt;

&lt;p&gt;For an organisation-scoped package, replace my-org in the command below with the name of your organisation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init --scope=@my-org
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For a user-scoped package, replace my-username in the command below with your username:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init --scope=@my-username
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You will get prompts requesting for &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;package name&lt;/li&gt;
&lt;li&gt;version&lt;/li&gt;
&lt;li&gt;description&lt;/li&gt;
&lt;li&gt;entry point&lt;/li&gt;
&lt;li&gt;test command&lt;/li&gt;
&lt;li&gt;git repository&lt;/li&gt;
&lt;li&gt;keywords&lt;/li&gt;
&lt;li&gt;author&lt;/li&gt;
&lt;li&gt;license&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This will be used to create a package.json for your project. Provide the requested information or press enter to use the default for each prompt. See the image below👇&lt;/p&gt;

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

&lt;p&gt;If successful, your project should have a package.json file with contents reflecting the information you provided. See the image below👇&lt;/p&gt;

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

&lt;h2&gt;
  
  
  Step 4: Write the code for your package
&lt;/h2&gt;

&lt;p&gt;Create the additional files: &lt;code&gt;converter.js&lt;/code&gt;, &lt;code&gt;index.js&lt;/code&gt; in your project.&lt;/p&gt;

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

&lt;p&gt;Copy and paste the cold below inside &lt;code&gt;converter.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
    /**
     * Converts a value to boolean
     * - "1", true, "true", "on", "yes", 1 converts to true while every other value converts to false
     * - value is not case sensitive
     * @param value the value (of type string|boolean|number) to be converted
     * @returns  a boolean
    */
    const convertToBoolean = (value) =&amp;gt; {
        try {

            if(value == undefined) throw new Error("No value provided");

            if (typeof value === "string") value = value.toLowerCase();
            const allowedTruthValues = ["1", "true", "on", "yes", 1, true];

            if (allowedTruthValues.includes(value)) return true;
            return false;

        } catch (error) {
            throw error;
        }
    }

module.exports = {convertToBoolean};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Copy and paste the code below inside &lt;code&gt;index.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const {convertToBoolean} = require("./converter")

module.exports = convertToBoolean
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 5: Test your package
&lt;/h2&gt;

&lt;p&gt;If you followed the previous steps correctly, your package should be ready now. To test it before publishing, create a new project; we will call it test-project. Initialise npm like we did in step 3. You can use default values all through as this is just for test purposes. Install your package in the test project using the npm install command: &lt;code&gt;npm install &amp;lt;full path to your project&amp;gt;&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install /users/username/folder-path/more-folder-path/boolean-converter
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create a &lt;code&gt;node_modules&lt;/code&gt; folder with your package in it. Import the exported function from your package like every other npm package you have used and test to make sure everything works fine.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feav012blumfkzhup6yum.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feav012blumfkzhup6yum.png" alt="Testing our new package in another project" width="800" height="427"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 6: Publishing your package to npm
&lt;/h2&gt;

&lt;p&gt;Now that everything works as expected, we are going to publish the package to npm.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Login to npm on your terminal. Head to npmjs.com and create an account if you don’t have any yet.&lt;/li&gt;
&lt;li&gt;From the root of your project on your terminal, run the command below
&lt;/li&gt;
&lt;/ol&gt;

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

&lt;/div&gt;



&lt;p&gt;You will get a prompt to login via your browser, press enter and complete the sign in process.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Back to your terminal, use the command to publish your package to the public on npm registry.
&lt;/li&gt;
&lt;/ol&gt;

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

&lt;/div&gt;



&lt;p&gt;If everything goes well, your package will be published to npm and your terminal should have a response similar to the screenshot below. You can go the npm website and search for the package with its name.&lt;/p&gt;

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

&lt;h2&gt;
  
  
  Publishing Scoped Packages
&lt;/h2&gt;

&lt;p&gt;By default, scoped packages are published with private visibility. To publish a scoped package with public visibility, pass the access flag when publishing the package.&lt;code&gt;--access public&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm publish --access public
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;If you followed along and everything worked fine, congratulations 🥂 , you have just published your first package to npm! 🥳&lt;/p&gt;

&lt;p&gt;Providing tools that make common tasks easier for other developers is always valuable and a great way to contribute to the community. The magic becomes very obvious when you shared a more efficient way of getting things done.&lt;/p&gt;

&lt;p&gt;Thank you for coming this far. The npm community await the amazing packages you will be publishing 🤝&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>node</category>
      <category>opensource</category>
      <category>npm</category>
    </item>
  </channel>
</rss>
