We are developing a Next.js frontend and an backend API that accepts Bearer Tokens (JWTs). We keep the backend separate for infrastructure and code management / framework reasons.
How is it possible to securely access the backend API from the Next.js frontend in the browser side?
I see in the official docs they only talk about “Access an External API from an API Route” (server-side) but what if I want to access an External API from a Page (browser-side)?
We have come up with the idea creating a NextJS backend endpoint just to pass the accessToken to the NextJS frontend so that it can directly call the External API without proxying through the NextJS backend.
This is our example code on the NextJS backend side:
import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0'
export default withApiAuthRequired(async function products(req: any, res: any) {
const { accessToken } = await getAccessToken(req, res, {
scopes: ['openid', 'profile', 'email', 'refresh_token']
})
res.status(200).json({ accessToken, message: 'Ready to call api with accessToken' })
}
})
Is this safe? - or better: Under what circumstances is this safe?
We understand the Access Token is a JWT with a fixed duration, that we intend to configure to be quite short (5-15min) so that they need to be frequently refreshed using the same method.