Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jvgrootveld/ed1863f0beddc1cc2bf2d3593dedb6da to your computer and use it in GitHub Desktop.
Save jvgrootveld/ed1863f0beddc1cc2bf2d3593dedb6da to your computer and use it in GitHub Desktop.
API Auth middleware for NextJS with firebase admin SDK as this does not work with _middleware files
import { auth } from '../../firebase/firebase-admin'
import { NextApiRequest, NextApiResponse } from 'next'
type NextContextApiHandler = (req: NextApiRequestWithContext, res: NextApiResponse) => Promise<void>
export interface Context {
uid: string
}
export interface NextApiRequestWithContext extends NextApiRequest {
context: Context
}
export const withAuth = (handler: NextContextApiHandler) => {
return async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
const authorization = req.headers.authorization
if (!authorization) {
return res.status(401).json({ message: 'Not authenticated. No Auth header.' })
}
const token = authorization.split(' ')[1]
const request = req as NextApiRequestWithContext
let decodedIdToken
try {
decodedIdToken = await auth.verifyIdToken(token)
if (!decodedIdToken || !decodedIdToken.uid) {
return res.status(401).json({ message: 'Not authenticated.' })
}
request.context = {
uid: decodedIdToken.uid,
}
} catch (error) {
console.log(`verifyIdToken error: ${error}`)
return res.status(401).json({ message: `Error while verifying token. Error: ${error}` })
}
return handler(request, res)
}
}
/*
Example use in api:
import type { NextApiResponse } from 'next'
import { firestore } from '../../../firebase/firebase-admin'
import { NextApiRequestWithContext, withAuth } from '../../lib/middlewares'
import { Profile } from '../../types'
const handler = async (req: NextApiRequestWithContext, res: NextApiResponse): Promise<void> => {
const collection = firestore.collection('profiles')
const document = await collection.doc(req.context.uid).get()
const data = document.data() as Profile
console.log(data)
return res.status(200).json(data)
}
export default withAuth(handler)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment