{"slug": "a-modern-guide-to-using-oauth-2-0-with-node-js", "title": "A Modern Guide to Using OAuth 2.0 with Node.js", "summary": "Dean Hume published a guide on 8 October 2026 showing how to implement the OAuth 2.0 client credentials flow in Node.js using only the @azure/msal-node package, relying on Node's built-in fetch and native .env loading (available since Node 20.6) to avoid node-fetch and dotenv. The guide requires Node.js 22 or later, stores CLIENT_ID, TENANT_ID, CLIENT_SECRET and SCOPES in a .env file, and acquires a Microsoft Entra ID access token via ConfidentialClientApplication.acquireTokenByClientCredential, run with the node --env-file=.env flag. Hume notes MSAL caches tokens in memory and warns developers to add .env to .gitignore before starting.", "body_md": "8 October 2026 · [Dean Hume](https://deanhume.com/about/)\n\n# A Modern Guide to Using OAuth 2.0 with Node.js\n\nEver followed an OAuth tutorial, copied the code, and then found out the library it uses was deprecated years ago? Yeah, me too. It's frustrating - especially when all you wanted was an access token.\n\nA little while ago I wrote [A Modern Guide to Using OAuth 2.0 with C# and Visual Studio Code](https://deanhume.com/a-modern-guide-to-using-oauth-2-0-with-c/), and it got a lot more attention than I expected. A few people asked if I could do the same thing for Node.js, so here it is.\n\nThis guide walks you through implementing OAuth 2.0 in Node.js using modern libraries and built-in features. No extra HTTP client, no config library - just a handful of lines of code and a working token at the end of it.\n\nWhether you're building a script, a back-end service, or an MCP server that needs to talk to a protected API (more on that in a future post), this is a clean place to start.\n\n## On this page\n\n### Prerequisites\n\nBefore we dive in, make sure you have the following:\n\n- [Node.js](https://nodejs.org/) 22 or later (anything from 20.6 will work for this guide, but I'd go with the current LTS)\n- [Visual Studio Code](https://code.visualstudio.com/)\n- A basic understanding of HTTP and REST APIs\n- A registered OAuth 2.0 application (e.g. via Google, Microsoft, or a custom provider)\n\nLet's get started!\n\n### Step 1: Create a New Node.js Project\n\nOpen your terminal and run:\n\n```\nmkdir oauth-node-demo\ncd oauth-node-demo\nnpm init -y\nnpm pkg set type=module\n```\n\nThat last line switches the project to ES modules, which means we can use `import` and top-level `await` without any extra setup.\n\n### Step 2: Install Required Packages\n\nSince I've already got an Entra app setup, we'll use `@azure/msal-node` to handle the OAuth flow for this example:\n\n```\nnpm install @azure/msal-node\n```\n\nThat's the only dependency. Node.js 18 and above ships with `fetch` built in, so we don't need `node-fetch` or anything else to make API calls. Since Node 20.6 can load `.env` files natively, we don't need `dotenv` either.\n\n### Step 3: Configure Your OAuth Settings\n\nCreate a `.env` file in the root of your project to store your credentials:\n\n```\nCLIENT_ID=your-client-id\nTENANT_ID=your-tenant-id\nCLIENT_SECRET=your-client-secret\nSCOPES=https://graph.microsoft.com/.default\n```\n\n🔍 **What is `tenant-id`?**\n\nThis is the unique identifier (GUID) for your Microsoft Entra ID tenant. You can find it in the Azure portal under Microsoft Entra ID > Overview. Alternatively, you can use your domain name (e.g. `contoso.onmicrosoft.com`) in place of the GUID. This might be different depending on your OAuth provider.\n\n⚠️ **Keep your secrets out of source control.**\n\nAdd `.env` to your `.gitignore` before you do anything else. I've seen more than one client secret accidentally pushed to a public repo, and it's not a fun clean-up job.\n\n```\necho \".env\" >> .gitignore\n```\n\n### Step 4: Authenticate and Acquire a Token\n\nCreate a file called `index.js` and add the following. It uses the client credentials flow, which is the right choice when your app is calling an API as itself rather than on behalf of a signed-in user:\n\n``` js\nimport { ConfidentialClientApplication } from \"@azure/msal-node\";\n\nconst { CLIENT_ID, TENANT_ID, CLIENT_SECRET, SCOPES } = process.env;\n\nconst msalClient = new ConfidentialClientApplication({\n  auth: {\n    clientId: CLIENT_ID,\n    authority: `https://login.microsoftonline.com/${TENANT_ID}`,\n    clientSecret: CLIENT_SECRET,\n  },\n});\n\nconst result = await msalClient.acquireTokenByClientCredential({\n  scopes: SCOPES.split(\",\"),\n});\n\nconsole.log(`Access Token: ${result.accessToken}`);\n```\n\nRun it with the `--env-file` flag so Node loads your `.env` file:\n\n```\nnode --env-file=.env index.js\n```\n\nIf everything is set up correctly, you'll see a long access token printed to the console. Congratulations - you just authenticated with OAuth 2.0!\n\nA quick note on tokens: MSAL caches them in memory for you, so calling `acquireTokenByClientCredential` again will return the cached token until it's close to expiring. You don't need to write your own refresh logic for this flow.\n\n### Step 5: Make an Authenticated API Call\n\nNow let's use that token to call a protected resource. Add this to the bottom of `index.js`:\n\n``` js\nconst response = await fetch(\"https://graph.microsoft.com/v1.0/users\", {\n  headers: {\n    Authorization: `Bearer ${result.accessToken}`,\n  },\n});\n\nif (!response.ok) {\n  throw new Error(`Request failed: ${response.status} ${response.statusText}`);\n}\n\nconst data = await response.json();\nconsole.log(JSON.stringify(data, null, 2));\n```\n\n✅ **Testing endpoint:** `https://graph.microsoft.com/v1.0/users`\n\nThis endpoint returns a list of users in your Entra ID tenant. To use it, make sure your app registration has the `User.Read.All` application permission and that you've granted admin consent.\n\nRun it again:\n\n```\nnode --env-file=.env index.js\n```\n\nIf all works as expected, you should see a response similar to this:\n\n```\n{\n  \"@odata.context\": \"https://graph.microsoft.com/v1.0/$metadata#users\",\n  \"value\": [\n    {\n      \"businessPhones\": [],\n      \"displayName\": \"Dean Hume\",\n      \"givenName\": \"Dean\",\n      \"jobTitle\": null,\n      \"mail\": null,\n      \"mobilePhone\": null,\n      \"officeLocation\": null,\n      \"preferredLanguage\": \"en\",\n      \"surname\": \"Hume\",\n      \"userPrincipalName\": \"email.com#EXT#@email.onmicrosoft.com\",\n      \"id\": \"id-response-goes-here\"\n    }\n  ]\n}\n```\n\nIf you get a `403` instead, it's almost always one of two things - the permission hasn't been added to your app registration, or admin consent hasn't been granted. I've lost more time to that second one than I'd like to admit.\n\n### Optional: Set up an Entra ID test OAuth App\n\nThis step is optional, as you might want to use your own OAuth provider. However, I wanted to be sure that my code actually worked, so I set up an app in [Microsoft Entra ID](https://www.microsoft.com/en-gb/security/business/identity-access/microsoft-entra-id) to test with.\n\nIf you'd like to do the same, these resources should help:\n\n### Conclusion\n\nOAuth 2.0 doesn't have to be intimidating. With a modern library like MSAL and the features that now ship with Node.js, you can securely authenticate and call a protected API in well under 30 lines of code - and with only one dependency.\n\nHave you run into any OAuth headaches when working with Node.js? I'd love to hear about them in the comments or over on GitHub - and if there's a flow you'd like me to cover next, let me know.", "url": "https://wpnews.pro/news/a-modern-guide-to-using-oauth-2-0-with-node-js", "canonical_source": "https://deanhume.com/a-modern-guide-to-using-oauth-2-0-with-node-js/", "published_at": "2026-10-08 00:00:00+00:00", "updated_at": "2026-11-03 10:35:53.018494+00:00", "lang": "en", "topics": ["developer-tools", "ai-agents"], "entities": ["Dean Hume", "Node.js", "Microsoft", "@azure/msal-node", "Microsoft Entra ID", "Visual Studio Code"], "also_reported_by": [], "takeaway": "Using @azure/msal-node's ConfidentialClientApplication with acquireTokenByClientCredential and running node --env-file=.env removes the need for node-fetch and dotenv, since Node 20.6+ loads .env files natively and Node 18+ ships fetch.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/a-modern-guide-to-using-oauth-2-0-with-node-js", "markdown": "https://wpnews.pro/news/a-modern-guide-to-using-oauth-2-0-with-node-js.md", "text": "https://wpnews.pro/news/a-modern-guide-to-using-oauth-2-0-with-node-js.txt", "jsonld": "https://wpnews.pro/news/a-modern-guide-to-using-oauth-2-0-with-node-js.jsonld"}}