Next.js
Integrate Passage into your Next.js application
Next.js is a front-end framework that builds additional functionality on top of React. Next.js by default pre-renders pages server-side to speed up delivering rendered pages and provide better SEO support. When using Passage in pre-rendered pages there are some specific changes to the standard React development workflow that need to be considered.
Importing and using the Passage-Auth Element from Passage-React
The easiest way to add authentication to a web frontend is with the Passage Provider and the Passage Auth elements from Passage-React. Passage-React handles registering the passage elements with the browser for you so the code is only executed when the client app is executed in browser. This ensures the passage elements are available out-of-the-box in your Next.js application without needing to worry about SSR pre-rendering.
npm i --save @passageidentity/passage-react
Then import <PassageProvider />
and PassageAuth
in the module where you intend to use the element:
import { PassageProvider, PassageAuth } '@passageidentity/passage-react';
// PassageProvider requires an App ID
// Home Route
'use client'; // For App Router
export default function Home() {
return (
<PassageProvider appId='YOUR_PASSAGE_APP_ID'>
<PassageAuth />
</PassageProvider>;
);
}
Getting Authentication Status and User Information with Server-Side Rendering
After the user has logged in with Passage, all requests need to be authenticated using the JWT provided by Passage. Use the Passage Node.js SDK (opens in a new tab) to authenticate requests and retrieve user data for your application, and other backend operations. Use passage-js (opens in a new tab) to perform client-side operations.
Using the Pages Router, you can handle authentication securely in Next.js's server-side rendering function getServerSideProps()
(opens in a new tab). Per Next.js documention you can import modules in top-level scope for use in getServerSideProps
. Imports used in getServerSideProps
will not be bundled for the client-side. This means you can write server-side code directly in getServerSideProps
.
Using the App Router, you will likely need to handle authentication by calling passage-node operations from server components and passage-js operations from client components.
The JWT provided by Passage is stored in both cookies and localstorage. Next.js provides the cookies set for an application to getServerSideProps
which allows passing the JWT from the client browser to the server to handle authentication.
Note: Handling authentication in a server-side pre-rendered function is not strictly necessary. If you prefer to call an authentication endpoint on your server after the page is delivered to the client you can still do so as you otherwise might in React