Member-only story

Getting started with NextAuth in server components (app router)

Geoffrey Rekier
3 min readJul 15, 2023

NextAuth is probably the most popular authentication library for NextJS at the moment and, I believe, is working quite well. But I think there is a hole in the documentation. And this is how to get it working with the App Router and only in server components.

To be fair, it is not a hole per se but more of a missing “Getting started” for it and the documentation around the app router setup is quite fragmented so here is my own.

The quick and dirty

For those who just want to make it work and have already set up everything else but get an error about context/provider in server components and don’t really care about using server components, there is the solution to just go through the barrier and use a context around the whole application with 'use client' around the whole app. You can do so by creating a component like this:

'use client'

import {SessionProvider} from 'next-auth/react'
import {ReactNode} from 'react'

export interface AuthContextProps {
children: ReactNode;
}

export default function AuthContext({children}: AuthContextProps) {
return <SessionProvider>{children}</SessionProvider>
}

and set wrap your application with <AuthContext>{children}</AuthContext> in your layout file. Now you can use next-auth…

--

--

Geoffrey Rekier
Geoffrey Rekier

Written by Geoffrey Rekier

Developer and tech enthusiast for more than 15 years. Mainly in the JVM for backend and quite a lot of Javascript/Typescript as well.

No responses yet