Next.js & External API without Proxying requests through Next.js backend

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.

Hello @felix3! Welcome to the community.

This is safe because the Next.js SDK is used for Regular Web App (RWA), which are private clients and can securely store secrets, specifically the client_secret. This is completely safe.

We do recommend short lived access tokens, but be cautious of hitting rate limits. It is possible to cache API Access Tokens which I’ll link here: Caching Management API Access Tokens in Login Action. This can help with using the same token instead of always getting a new one and can be done using actions.

Here are some more docs that may help:

Get Management API Access Tokens for Production

I hope this helps!

Best,
Alex

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.

Hey team!

If you’re curious about the new Auth0 Next.js SDK and how it works with Next.js 15 and Turbopack, now’s a great time to get involved!

We’re hosting an Ask Me Anything session with Kevin Lillybridge, Auth0’s Group Product Manager, on December 10, from 9 AM to 11 AM PST. You’ll receive detailed, written answers straight from the experts - plus earn a special badge. Don’t miss this opportunity to gain valuable insights and supercharge your Next.js development!

Auth0 by Okta Community Ask Me Anything: Unlocking the Power of the Auth0 and Next.js