Contember authentication in Next.js #761
-
Hi! I'm building a CMS using Contember and Next.js and I’d like to ask for some guidance on how to properly set up Contember authentication in the Next.js. I’ve been told it’s quite straightforward and that I should ask here in discussions. Could you please explain what needs to be done or point me to an example? Thanks a lot in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi there! Integrating Contember authentication into a Next.js app breaks down into two parts: configuring Contember Engine’s Tenant API (for sessions and invitations) and wiring up Next.js to issue, consume, and protect those sessions. Here’s a concise, step‑by‑step outline: 1. Configure Contember sessions # Example: sign in
mutation {
signIn(email: "[email protected]", password: "secret", expiration: 60) {
ok
result { token }
error { code }
}
}
# Example: sign out (current session)
mutation {
signOut { ok }
} This token is what you’ll use as your session credential in Next.js. 2. (Optional) Onboard users via invitations mutation {
invite(
email: "[email protected]",
projectSlug: "my-blog",
memberships: [{ role: "editor", variables:[{name:"language",values:["en"]}] }],
options: { method: RESET_PASSWORD }
) {
ok
error { code }
}
} That kicks off your email flow so the user can set their password and sign in. 3. Create Next.js API routes to proxy Contember calls
// pages/api/auth/login.ts
import type { NextApiRequest, NextApiResponse } from 'next'
import { serialize } from 'cookie'
import { GraphQLClient, gql } from 'graphql-request'
const client = new GraphQLClient(process.env.CONTEMBER_TENANT_API_URL!, {
headers: { Authorization: `Bearer ${process.env.CONTEMBER_LOGIN_TOKEN}` }
})
const SIGN_IN = gql`
mutation SignIn($email: String!, $password: String!) {
signIn(email: $email, password: $password, expiration: 60) {
ok
result { token }
error { code }
}
}
`
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { email, password } = req.body
const { signIn } = await client.request(SIGN_IN, { email, password })
if (!signIn.ok) {
return res.status(401).json({ error: signIn.error.code })
}
const cookie = serialize('session', signIn.result.token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 24, // 1 day
path: '/',
})
res.setHeader('Set-Cookie', cookie)
res.status(200).json({ success: true })
} This pattern follows the Next.js “Authentication” guide for API Routes. 4. Handle sign‑out // pages/api/auth/logout.ts
import type { NextApiRequest, NextApiResponse } from 'next'
import { serialize } from 'cookie'
import { GraphQLClient, gql } from 'graphql-request'
const client = new GraphQLClient(process.env.CONTEMBER_TENANT_API_URL!, {
headers: { authorization: `Bearer ${req.cookies.session}` }
})
const SIGN_OUT = gql`mutation { signOut { ok } }`
export default async function handler(_req: NextApiRequest, res: NextApiResponse) {
await client.request(SIGN_OUT)
res.setHeader('Set-Cookie', serialize('session', '', { maxAge: 0, path: '/' }))
res.status(200).json({ success: true })
} 5. Protect pages and API routes // middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { cookies } from 'next/headers'
export function middleware(req: NextRequest) {
const session = cookies().get('session')?.value
const url = req.nextUrl.clone()
if (!session && url.pathname.startsWith('/dashboard')) {
url.pathname = '/login'
return NextResponse.redirect(url)
}
return NextResponse.next()
}
export const config = { matcher: ['/dashboard/:path*'] } This aligns with Next.js’s recommended “Optimistic checks with Middleware” pattern. Further resources
With those pieces in place you’ll have secure, Contember‑powered authentication in your Next.js app. Good luck! |
Beta Was this translation helpful? Give feedback.
Hi there!
Integrating Contember authentication into a Next.js app breaks down into two parts: configuring Contember Engine’s Tenant API (for sessions and invitations) and wiring up Next.js to issue, consume, and protect those sessions. Here’s a concise, step‑by‑step outline:
1. Configure Contember sessions
Contember exposes a GraphQL Tenant API for user sessions. To sign in, call the
signIn
mutation (providing email, password and an optional expiration) and grab the returned session token. To log out, call thesignOut
mutation.