Skip to content

Latest commit

 

History

History
192 lines (146 loc) · 4.4 KB

File metadata and controls

192 lines (146 loc) · 4.4 KB

import { Callout } from "nextra/components" import { Code } from "@/components/Code"

Get Session

Once a user is logged in, you often want to get the session object in order to use the data in some way. A common use-case is to show their profile picture or display some other user information.

import { auth } from "../auth"

export default async function UserAvatar() {
  const session = await auth()

  if (!session.user) return null

  return (
    <div>
      <img src={session.user.img} alt="User Avatar" />
    </div>
  )
}

</Code.Next> <Code.NextClient>

In the pages router, to access a session in a component, you'll first need to get the session object in a page and then pass it down to the component.

Page Server Side

import { auth } from "@/auth.ts"
import { UserAvatar } from "@/components/UserAvatar"

export default function Dashboard({ session }) {
  return (
    <nav>
      <UserAvatar session={session} />
    </nav>
  )
}

export async function getServerSideProps(ctx) {
  const session = await auth(ctx)

  return {
    props: {
      session,
    },
  }
}

Page Client Side

When accessing the session client-side using useSession(), make sure an Auth.js <SessionProvider /> is wrapping your page.

import type { AppProps } from "next/app"
import { SessionProvider } from "next-auth/react"

export default function MyApp({
  Component,
  pageProps: { session, ...pageProps },
}: AppProps) {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />;
    </SessionProvider>
  )
}
import { useSession } from "next-auth/react"
import { UserAvatar } from "@/components/UserAvatar"

export default function Dashboard() {
  const session = useSession()

  return (
    <nav>
      <UserAvatar session={session} />
    </nav>
  )
}

Finally, we can use it in the component.

export function UserAvatar({ session }) {
  return (
    <div>
      <img
        src={session?.user.img ?? "https://source.boringavatars.com/marble/120"}
        alt="User Avatar"
      />
    </div>
  )
}

</Code.NextClient> <Code.Svelte>

With SvelteKit, you have to return the session object from the load function in your +page.server.ts or +layout.server.ts files.

import type { PageServerLoad } from "./$types"

export const load: PageServerLoad = async (events) => {
  const session = await events.locals.auth()

  if (!session?.user?.userId) {
    redirect(303, `/login`)
  }

  return {
    session,
  }
}

Then you can access the session on the $page.data object in your page.

<script lang="ts">
  import { page } from "$app/stores"
</script>

<nav>
  <img
    src={$page.data.session?.user?.image ?? 'https://source.boringavatars.com/marble/120/'}
    alt="User Avatar"
  />
</nav>

</Code.Svelte> <Code.Express>

import { getSession } from "@auth/express"

export function authSession(req: Request, res: Response, next: NextFunction) {
  res.locals.session = await getSession(req)
  next()
}

app.use(authSession)

// Now in your route
app.get("/", (req, res) => {
  const { session } = res.locals
  res.render("index", { user: session?.user })
})

</Code.Express> <Code.Fastify>

import { getSession } from "@auth/fastify"

// Decorating the reply is not required but will optimise performance
// Only decorate the reply with a value type like null, as reference types like objects are shared among all requests, creating a security risk.
fastify.decorateReply("session", null)

export async function authSession(req: FastifyRequest, reply: FastifyReply) {
  reply.session = await getSession(req, authConfig)
}

fastify.addHook("preHandler", authSession)

// Now in your route
fastify.get("/", (req, reply) => {
  const session = reply.session
  reply.view("index", { user: session?.user })
})

Note for TypeScript, you may want to augment the Fastify types to include the session property on the reply object.

</Code.Fastify>

If you'd like to extend your session with more fields from your OAuth provider, for example, please check out our "extending the session" guide.