Follow these simple steps to set up Civic Auth with an Express backend (a working example is available in our github examples repo).
1. Install dependencies
npminstall@civic/authcookies-parser
yarnadd@civic/authcookies-parser
pnpminstall@civic/authcookies-parser
bunadd@civic/authcookies-parser
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 express, { Request, Response } from'express';import { CookieStorage } from'@civic/auth/server';import cookieParser from'cookie-parser';app.use(cookieParser());// Tell Civic how to get cookies from your node serverclassExpressCookieStorageextendsCookieStorage {constructor(private req:Request,private res:Response) {super({ secure:false }) }asyncget(key:string):Promise<string|null> {returnPromise.resolve(this.req.cookies[key] ??null); }asyncset(key:string, value:string):Promise<void> {awaitthis.res.cookie(key, value,this.settings); }}app.use((req, res, next) => {// add an instance of the cookie storage to each requestreq.storage =newExpressCookieStorage(req, res);next();});
4. Create a Login Endpoint
This endpoint will handle login requests, build the Civic login URL and redirect the user to it.
import { isLoggedIn } from'@civic/auth/server';constauthMiddleware=async (req:Request, res:Response, next:NextFunction) => {if (!(awaitisLoggedIn(req.storage))) returnres.status(401).send('Unauthorized');next();};// Apply authentication middleware to any routes that need itapp.use('/admin', authMiddleware);
8. Use the Session
If needed, get the logged-in user information.
import { user } from'@civic/auth/server';app.get('/admin/hello',async (req:Request, res:Response) => {constuser=awaitgetUser(req.storage);res.send(`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.