Follow these simple steps to set up Civic Auth with a Fastify backend.
1. Install dependencies
npminstall@civic/auth@fastify/cookie
yarnadd@civic/auth@fastify/cookie
pnpminstall@civic/auth@fastify/cookie
bunadd@civic/auth@fastify/cookie
2. Configure your App
Your app will need the following configuration:
constconfig= { clientId:// Client ID from auth.civic.com redirectUrl: 'http://localhost:3000/auth/callback',// change to your domain when deploying postLogoutRedirectUrl:'http://localhost:3000/'// The postLogoutRedirectUrl is the URL where the user will be redirected after successfully logging out from Civic's auth server.};
Note: redirectUrl and postLogoutRedirectUrl must be absolute URLs.
3. Set up Cookies
Civic Auth uses cookies for storing the login state by default
import Fastify, { FastifyReply, FastifyRequest } from'fastify';import fastifyCookie from'@fastify/cookie';import { CookieStorage } from'@civic/auth/server';constfastify=Fastify().register(fastifyCookie, { secret:"my-secret",// should be changed in production parseOptions: {}})classFastifyCookieStorageextendsCookieStorage {constructor(private request:FastifyRequest,private reply:FastifyReply) {super(); }asyncget(key:string):Promise<string|null> {returnPromise.resolve(this.request.cookies[key] ??null); }asyncset(key:string, value:string):Promise<void> {awaitthis.reply.setCookie(key, value,this.settings); }}// attach an instance of the cookie storage to each requestfastify.decorateRequest('storage',null);fastify.addHook('preHandler',async (request, reply) => {request.storage =newFastifyCookieStorage(request, reply);});
4. Create a Login Endpoint
This endpoint will handle login requests, build the Civic login URL and redirect the user to it.
import { user } from'@civic/auth/server';fastify.get('/admin/hello',async (request, reply) => {constuser=awaitgetUser(request.storage);return`Hello, ${user?.name}!`;});
PKCE and Client Secrets
Civic Auth uses PKCE (Proof Key for Code Exchange), to protect users and clients from unauthorized access to user information. This, alongside domain registration for apps in production environments, mean that you don't need to provide a client secret in your backend.
When using the Civic Auth SDK, PKCE is handled entirely by the library.