This demo show-cases an approach to using NextAuth in an Express backend.
- Install dependencies with
pnpm install
The project uses
pnpm
but you can also install dependencies withnpm
oryarn
- Run the development server
pnpm dev
- First create a router that bundles together all of
next-auth
's authentication routes and functionality. In this demo, the generic router is defined insrc/routes/auth.routes.ts
. - Next, we make sure to use or apply 3 important middleware to the application. These include
express.json()
,cookieParser()
, andexpress.urlencoded()
. - After these are in place, we
app.use(nextAuthRouter({ basePath: "/api/auth", authOptions }))
by providing it a base path andauthOptions
(as you would in Next.js) - Finally, make sure to define all required environment variables for
next-auth
and its providers, similar to those in.env.example
With that everything is good to go!
The Next.js Pages Router and Express Framework extend the same Request
and Response
interfaces with additional some common functionality. While the compatibility is not 1:1, it is enough such that next-auth
(v4) is cross-compatible.
For example, methods such as
res.send()
, andres.json()
are implemented across both response types. However methods such asres.revalidate()
exist in Next.js land only. This is okay since the method is not used in NextAuth (v4).
Aside these interface differences, there are two caveats with Express:
- Making sure we apply some middleware functions (Step 2) in order to parse and fill some request object properties in Express.
- Manually parsing the request path into the Catch-all Dynamic Segments as is done automatically in Next.js. This is specifically relied on by NextAuth.
This demo was adapted from: