How to Securely and Efficiently Store a nonce Value in a Next.js Application?

  Kiến thức lập trình

I am developing a Next.js application that requires interacting with an external API. Each request to this API must include a unique nonce value that is provided by the API with each response. I need to store this nonce value securely and efficiently for use in subsequent requests.

Issue:

I attempted to use cookies via next/headers to store the nonce value, but I am unable to retrieve and pass it effectively in new requests to different endpoints. Specifically, I tried setting a cookie in the route handler and then accessing it in a middleware (/src/middleware.tsx), but the cookie data was not being retained.

Code Example:

Here is how I am fetching data in /app/page.tsx:

const fetchData = async () => {
  const response = await fetch(`${process.env.API_URL}/api/endpoint`);
  if (!response.ok) { throw new Error('Failed to fetch data'); }
  return response.json();
}

const Page = async () => {
  const response = await fetchData();
  return (
    <>
      {JSON.stringify(response)}
    </>
  );
}

export default Page;

And here is how I am handling the API endpoint in /app/api/endpoint/route.tsx:

import { NextRequest, NextResponse } from "next/server";
const EXTERNAL_API_URL = `${process.env.EXTERNAL_API_URL}/my-endpoint`;

export async function GET(request: NextRequest) {
  const apiResponse = await fetch(EXTERNAL_API_URL);
  const data = await apiResponse.json();
  const nonce = apiResponse.headers.get('nonce');

  const response = NextResponse.json(data);
  if (nonce) {
    // Intend to use this nonce value in future client requests
  }

  return response;
}

Question:

How can I securely and efficiently store and retrieve the nonce value in my Next.js application to ensure it can be used in future requests? What are best practices for managing such dynamic data in a client-server architecture like Next.js?

LEAVE A COMMENT