What is the best way to obtain the idToken from Auth0 in a React component or a regular function within a NextJs application?

I'm currently developing a NextJs application and I need to include the idToken in all backend calls. Is there an efficient method to implement this? Here's a simplified overview of our app structure:

We have a page:

/* src/pages/example/index.page.tsx */

export const getServerSideProps: GetServerSideProps<ExamplePageProps> = async (
  context,
) => {
  const initialTranslations = await getTranslations(context.locale, ['example']);
  return {
    props: {
      initialTranslations,
    },
  };
};

export interface ExamplePageProps {
  ...
}

function ExamplePage(props: ExamplePageProps) {
  return (
    <MyComponent />
  );
}

The component is as follows:

/* src/pages/components/MyComponent/MyComponent.tsx */

export const MyComponent: FC<MyComponentProps> = (...) => {
  const handleClick = async () => {
    await makeBackendCall(param1, param2);
  }

  ...
  <Button onClick={handleClick} />
  ...
}

The backend call is located here:

/* src/fetchers/webapi.ts */

export const makeBackendCall = (param1: string, param2: string): Promise<Response> => {
  fetch('http://some.url', {
    method: 'GET',
    headers: {
      /* *** THIS IS WHERE I NEED TO SEND idToken *** */
    }
  });
}

export const anotherCallWhichNeedsTheToken = () => {...}
export const andAnotherOne = () => {...}
/*...*/

How can I go about achieving this? Thus far, my closest attempt has been fetching it in getServerSideProps, like so:

import { getSession } from '@auth0/nextjs-auth0';
...
const session = getSession(context.req, context.res);
const idToken = session?.idToken;
...
return {
    props: {
      initialTranslations,
      idToken,
    },
};

...or more generally:

return {
  props: {
    initialTranslations,
    session: getSession(context.req, context.res),
  },
};

...but in either case, I encounter a compiler error with getServerSideProps, mentioning something about incompatible props (I believe it is related to returning a promise in getServerSideProps and specifying a "regular" object in component props, although I am uncertain).

Answer №1

The idToken is secured within an encrypted HttpOnly cookie, making it accessible only through backend code.

When making fetch requests to APIs on the same domain as the client, there is no need to manually pass the idToken since cookies are automatically included in each request. To access them from the API, you can utilize the getSession function.

If data needs to be retrieved from a different domain, one approach is to create a proxy API in nextjs where the proxy API can handle the communication with the external domain without requiring the idToken to be passed directly from the client.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a 404 error page when attempting to access the NextJs App build, even though it is functioning perfectly in development mode

As a newcomer to React/Next JS, I encountered an issue after purchasing a theme and customizing the configuration and branding. Running the app with "yarn dev" and "yarn start" works fine, and "yarn build" produces an optimized production build. In my atte ...

Can you update the `runtime` property to `segment` in the export config?

I'm currently working on setting up an upload API route within my application. /admin/upload However, when I attempt to console.log(req.file), it returns as undefined. This seems to be related to the following configuration: export const config = { ...

Nextjs doesn't render the default JSX for a boolean state on the server side

I am working on a basic nextjs page to display a Post. Everything is functioning smoothly and nextjs is rendering the entire page server side for optimal SEO performance. However, I have decided to introduce an edit mode using a boolean state: const PostPa ...

Encountering a "Type expected" error in NPM when compiling a React/Next.js project following the integration of use-places

While building my React/Next.js project, I encountered an error. Even after attempting to open VS Code as an administrator, the issue persisted. ./node_modules/use-places-autocomplete/dist/index.d.ts:21:24 Type error: Type expected. 19 | export type S ...

Error: The property 'insertAfter' of the variable is not defined and cannot be read

While attempting to launch the frontend of my project (built in next.js) using 'yarn dev', I encountered this error message: error - ./node_modules/next/dist/compiled/css-loader/cjs.js??ruleSet[1].rules[2].oneOf[6].use[1]!./node_modules/next/dist ...

Tips for activating the default 500 error page in Next.js

I'm having trouble getting Next.js to display its default 500 error page. While most sources discuss creating a custom error page, the Next.js documentation only briefly references their built-in 500 error page. I want the default page to show up when ...

Production environment exclusively experiencing Next Auth Azure App Service 500 error

My Nextjs application is hosted on Azure App Services using Next Auth, with both AzureADProvider and EmailProvider being utilized. In the development slot of my Azure app service, both AzureADProvider and EmailProvider are functioning correctly. However, ...

Trouble arises with Service Workers during the transition from Create React App to Next JS

After transitioning our landing page from create-react-app to Next.js, we encountered an issue with users receiving a cached version of the old website. This is due to the default service worker that was registered on their browsers when using create-react ...

Issue with image paths in the shared layout across multiple pages

My Next.js application is experiencing an issue with a shared layout component used on multiple pages. The layout contains an image in the navbar that displays correctly on the home page. However, when navigating to other pages, the image path seems to be ...

"Encountering a 404 error with NextAuth when deploying on Verc

My current setup involves using a CustomProvider as a Python backend server for app authentication: import CredentialsProvider from 'next-auth/providers/credentials' import NextAuth from 'next-auth' import { postLogin } from '../.. ...

Utilizing a third-party API within the next/api endpoint

I've recently started working with NEXTJS and developed a weather application. I'm integrating the openweather API, but I'm unsure how to use it within the next/api. I attempted creating a file named today.js inside the next/api directory an ...

Steps to forward a restricted user to a specific webpage

I am currently utilizing NextJs and am in the process of creating a redirecting function for users who have been banned or blocked from accessing the DB/session. My attempt at this involved: redirect.js, where I created a custom redirect function. impo ...

Troubleshooting: Next.js application deployment on Azure Web App encountering file discrepancies

I'm currently facing an issue while attempting to deploy a next.js (with typescript) application on Azure using Bitbucket pipelines. As part of my pipeline process, I build the next.js app with the following build configuration: // next.config.js /** ...

TypeError was not handled: Attempted to use the 'in' operator to search for 'electron' in an undefined variable at next-dev.js line 8

I encountered an unexpected error while attempting to run next.js in development mode. The strange part is that I'm not utilizing electron in this application at all. An uncaught TypeError occurred: Cannot use 'in' operator to search for &a ...

Import MDX metadata in Next.js on the fly

I am currently utilizing Next.js to create a static blog site. Following the guidelines in Next.js documentation, I set up @next/mdx and successfully imported MDX statically using import MDXArticle from "@/app/(article)/2023/test-article/page.mdx&quo ...

Tips on preventing repeated data fetching logic in Next.js App Routes

I'm currently developing a project with Next.js 13's latest App Routes feature and I'm trying to figure out how to prevent repeating data fetching logic in my metadata generation function and the actual page component. /[slug]/page.tsx expo ...

Exploring the characteristics of images within the framework of Next.js

I am currently experimenting with the Next.js Image Component in my component to enable Automatic Image Optimization. import Image from "next/image"; const PicArrs = () => ( <Image src="remote-location" alt="ViewCrunch&quo ...

Tips for utilizing a confidential key to trigger on-demand revalidation for ISR (Next.js) on the client side while keeping it secure from exposure

The documentation suggests using a SECRET_TOKEN to secure access to your revalidate API route, as shown here: https://<your-site.com>/api/revalidate?secret=<token> However, the challenge lies in maintaining secrecy of the token when calling t ...

The Kuma CSS in JS library assigns a class, however it does not produce any visible changes

I've implemented Kuma.js as my CSS in JS solution for Next JS 13. I'm currently working on styling a Header component called HeaderWrapper using Kuma. Below is the code snippet: import { styled } from "@kuma-ui/core"; const HeaderWrapp ...

Obtaining the true client IP address in a Dockerized Next.js and Nestjs application instead of the Nginx Container's IP Address | Utilizing X-Forwarded-For

I have successfully Dockerized both Next.js 13 (front end) and Nestjs (API), with a reverse proxy set up using the nginx-proxy image. Below is my configuration in the docker-compose.yml: api: image: gidgud/my:api container_name: api ports: ...