Enable your Next.js Single-Page Application (SPA) to sign-in users and call APIs with the Microsoft identity platform
An example showcasing the core principles of modern authentication using the Microsoft Identity Platform in Next.js version 14, utilizing MSAL React for client-side requests to Microsoft Graph.
The Microsoft identity platform, incorporating Entra ID (Azure AD) and Azure Azure Active Directory B2C (Azure AD B2C) plays a pivotal role in the Azure cloud ecosystem. This example is designed to showcase the basics of modern authentication within a Next.js framework, utilising the Microsoft Authentication Library for React (MSAL React).
Next.js is an open-source React front-end development framework that enables developers to build server-side rendering and static web applications. It's known for its features like automatic code splitting, optimized performance, and simple page-based routing system, as well as for supporting static site generation (SSG), server-side rendering (SSR), and incremental static regeneration (ISR), making it a versatile choice for developing highly efficient and scalable web applications.
- Node.js
- Next.js v14.1.0+
- Visual Studio Code
- A modern web browser
- Next.js by Vercel framework documentation
- SWR by Vercel React Hooks for Data Fetching
âšī¸ "SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data."
- jwt.ms for inspecting your tokens
- Microsoft Authentication Library (MSAL) for JS
- SPA developers: Migrate implicit to auth code flow with PKCE
- Follow the Entra ID Blog to stay up-to-date with the latest developments
./authConfig.ts
Configuration of MSAL./utils/NavigationClient.ts
The AppRouterInstance and Next.js./utils/msGraphFetcher.ts
Implementation of the SWR Fetcher instance for MS Graph calls including the access token../utils/MsalHelper.ts
Token acquisition from the MSAL library../components/ProfileData.ts
Consuming the SWR service without needing to use props from a parent component.
- Open ./authConfig.ts in an editor.
- Replace NEXTJS_APP_CLIENT_ID with the Application (client) ID from your created Entra Application Registration.
- Replace NEXTJS_APP_AUTHORITY with the Entra Tenant Id of your environment.
# Install dependencies from the root of the repo
npm install
# Run locally
npm run dev
# Optionally build
# npm run build
- Open http://localhost:3000 to view in your browser.
- Open http://localhost:3000/profile to view a protected route, that if signed in will display profile information.
- Open http://localhost:3000/example to see an unprotected route.
- The current version of Next.js does not correctly handle redirect requests. So in this sample the popup method is used.