# How to validate a token on Next.js backend from a separate frontend

**URL:** <https://community.auth0.com/t/how-to-validate-a-token-on-next-js-backend-from-a-separate-frontend/103328>\
**Category:** Get Help\
**Tags:** sdks-quickstarts, nextjs-auth0\
**Created:** [March 25, 2023, 5:17pm UTC](https://community.auth0.com/t/how-to-validate-a-token-on-next-js-backend-from-a-separate-frontend/103328 "2023-03-25T17:17:47Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![DavidTheo](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@DavidTheo](https://community.auth0.com/u/DavidTheo)\
**Post date:** [March 25, 2023, 5:17pm UTC](https://community.auth0.com/t/how-to-validate-a-token-on-next-js-backend-from-a-separate-frontend/103328/1 "2023-03-25T17:17:47Z")

</div>

I host a backend via Next.js on Vercel. In a separate hosted frontend which is not in the same Next.js repo the user authenticates via Auth0. Therefor, I created a Single Page Application in my Auth0 account. I get the token in the frontend and send it with the API call to the backend. Everything works smoothly. Now I want to protect the backend API.

With Next.js I created a middleware in which I want to validate the token for every API call. The token also arrives. How can I validate the token now?

I have not found a solution that I understood right away.

1. I created an API in my Auth0 account. In the quick start tutorial, a Node.js solution is shown. Since I use Next.js I didn’t manage to enforce the endpoints via `app.use(jwtCheck)`. I don’t know how to do this because I don’t have access to the express app on Next.js?

2. All other solutions I found work with the Next.js session. Since my frontend is hosted on another repo separately, I can’t do anything with the solutions.

_React Frontend (localhost:4040)_

```auto

import {useAuth0} from "@auth0/auth0-react";
const auth = useAuth0();
const token = await auth.getAccessTokenSilently();
await axios.get('http://localhost:3000/api/users',
  {
    headers: {Authorization: `Bearer ${token}`}
  }
).then(console.log).catch(console.log);

```

_Next.js Backend - middleware.ts - (localhost:3000)_

```auto
import {NextRequest, NextResponse} from 'next/server'
export async function middleware(req: NextRequest) {
    const token = req.headers.get("Authorization");
    console.log(token)
}

```

---

<div class="post-metadata">

**Author:** ![DavidTheo](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@DavidTheo](https://community.auth0.com/u/DavidTheo)\
**Post date:** [March 28, 2023, 6:49pm UTC](https://community.auth0.com/t/how-to-validate-a-token-on-next-js-backend-from-a-separate-frontend/103328/2 "2023-03-28T18:49:34Z")

</div>

I have just discovered [Jose](https://www.npmjs.com/package/jose) and managed the problem.

```auto
import {NextRequest, NextResponse} from 'next/server'
import * as jose from 'jose';

export async function middleware(req: NextRequest) {
  if (req.method === 'OPTIONS') {
    return NextResponse.json({});
  }

  const token = req.headers.get("Authorization");
  if (token) {
    await authenticateRequest(token);
  } else {
    return new NextResponse(
            JSON.stringify({success: false, message: 'Authentication failed: No token given'}),
            {status: 401, headers: {'content-type': 'application/json'}}
        );
    }
}

async function authenticateRequest(token: string) {
    // Load public key from authentication provider
    const jwks = jose.createRemoteJWKSet(new URL(process.env.AUTH0_JWKS_URI!));
    try {
        // Verify the given token
        const result = await jose.jwtVerify(token.replace('Bearer ', ''), jwks);
        return NextResponse.next();
    } catch (e) {
        console.error('Authentication failed: Token could not be verified')
        return new NextResponse(
            JSON.stringify({success: false, message: 'Authentication failed: Token could not be verified'}),
            {status: 401, headers: {'content-type': 'application/json'}}
        );
    }
}

```

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [March 28, 2023, 11:18pm UTC](https://community.auth0.com/t/how-to-validate-a-token-on-next-js-backend-from-a-separate-frontend/103328/3 "2023-03-28T23:18:17Z")

</div>

Hey there @DavidTheo thanks for following up on this one with your solution - That’s correct though, we typically recommend using a library [here](https://jwt.io/libraries) (jose included) or something like:

> **[node-oauth2-jwt-bearer/packages/express-oauth2-jwt-bearer at main ·...](https://github.com/auth0/node-oauth2-jwt-bearer/tree/main/packages/express-oauth2-jwt-bearer)**
>
> main/packages/express-oauth2-jwt-bearer

Cheers!

---

<div class="post-metadata">

**Author:** ![DavidTheo](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@DavidTheo](https://community.auth0.com/u/DavidTheo)\
**Post date:** [March 28, 2023, 11:32pm UTC](https://community.auth0.com/t/how-to-validate-a-token-on-next-js-backend-from-a-separate-frontend/103328/4 "2023-03-28T23:32:06Z")

</div>

Yes I came across that too, but I didn’t understand how to use middleware in Next.js at first to build something similar without express.

---

<div class="post-metadata">

**Author:** ![bogadrian](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/bogadrian/32/46170_2.png) [@bogadrian](https://community.auth0.com/u/bogadrian)\
**Post date:** [April 8, 2023, 9:06am UTC](https://community.auth0.com/t/how-to-validate-a-token-on-next-js-backend-from-a-separate-frontend/103328/5 "2023-04-08T09:06:01Z")

</div>

Yes but that means asking the Jwt keys on each request. Those keys should be cached.

---

<div class="post-metadata">

**Author:** ![DavidTheo](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@DavidTheo](https://community.auth0.com/u/DavidTheo)\
**Post date:** [April 8, 2023, 10:40am UTC](https://community.auth0.com/t/how-to-validate-a-token-on-next-js-backend-from-a-separate-frontend/103328/6 "2023-04-08T10:40:22Z")

</div>

Good point. I am using a serverless architecture. The public key does not change, does it? So I could use it as an environment variable.

---

<div class="post-metadata">

**Author:** ![bogadrian](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/bogadrian/32/46170_2.png) [@bogadrian](https://community.auth0.com/u/bogadrian)\
**Post date:** [April 8, 2023, 10:50am UTC](https://community.auth0.com/t/how-to-validate-a-token-on-next-js-backend-from-a-separate-frontend/103328/7 "2023-04-08T10:50:04Z")

</div>

Sure. That applies only if you rotate the signin key regularly.

> **[Signing Keys](https://auth0.com/docs/get-started/tenant-settings/signing-keys)**
>
> Describes how your tenant's application signing keys work.

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/auth0/original/3X/b/5/b560f266932fcce5d57f09a6595bd50518cae3f3.jpeg) [@system](https://community.auth0.com/u/system)\
**Post date:** [April 22, 2023, 10:50am UTC](https://community.auth0.com/t/how-to-validate-a-token-on-next-js-backend-from-a-separate-frontend/103328/8 "2023-04-22T10:50:19Z")

</div>

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