Using Next.js 13 for authentication between server-side components and a separate backend

Looking for guidance on how to execute API requests from Nextjs 13 to a separate Python backend.

I am faced with two different scenarios:

  • API request made from client-side component
  • API request made from server-side component

When the request originates from the client-side component, it includes the correct session cookie from my authentication provider (Clerk). This allows for straightforward authentication in the Python backend.

However, when the request comes from the server-side, session cookies are not present. One option could be to include a JWT token, but this would complicate the process.

What approach do you suggest for handling this particular scenario?

Answer №1

I'm facing the same uncertainty about how to tackle this issue. In my particular situation, the backend can either send a jwt token in response or as a cookie. My goal is to fetch user data on the server and transmit it to the browser in order to avoid any flashing screens.

A potential solution could be:

When the external server sends the jwt token, Next.js cannot store it internally. It must be kept within the user's browser. Thus, the workflow would look like this:

Request

User browser (login page) -> Next.js API -> External Server (Login route)

Response

External server (JWT TOKEN) -> Next.js API (Set cookie in user browser) -> User browser

From now onwards, whenever a request is made to any page, the cookie will be available for access in the next server component. This allows for making requests to external server APIs using the stored cookie.

Please share if there exists a better approach that could be taken.

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

Dealing with Excessive Requests in a NextJS Application Routing Layout

Currently, I am developing a NextJS application with an app router that will feature a navigation component. Within this navigation, it is essential to display user information such as a username and avatar. I attempted to implement a layout file based on ...

The occurrence of TypeError in next.js Dropzone stating that (0 , _mantine_core__WEBPACK_IMPORTED_MODULE_0__.rem) is not a function is indicating

I am encountering an issue while trying to render a dropzone component using Next.js and Mantine. For reference, I am following the documentation at . Here is the import statement: import dropzone I am receiving an error message that says: I have inclu ...

Retrieving Data from Class Component in a Functional Component using React

I am currently utilizing a React module called react-semantic-ui-datepickers, which I believe is built upon react-datepicker. Nonetheless, this is more of a general React query. In my file, I have both my main class component and the date picker functional ...

Dealing with the issue of needing to include "%20" in the URL after receiving a NextJS build

Currently, I am working on a simple NextJS (v13) project utilizing TheMoviedb API. I am fetching images and titles of content with an API request in this project. The image paths can be accessed using a variable named dt, which corresponds to either backdr ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

A more advanced approach to validating form input in React/Next Js

I have designed a basic form for my web application. I am considering adding a feature to validate all fields, ensuring they are not empty and displaying an error message if necessary. Here is the outline of what I have so far: import { useState } from &ap ...

Send a property as a string, then transform the string back into JavaScript

I am in the process of creating a versatile carousel that will cater to various conditions. Therefore, I need to set the "imageQuery" on my display page as a string and then make it work as executable javascript within my carousel. The query functions pr ...

Website created using React without the use of Javascript

Currently, I am considering migrating one of my websites that is built using Python-Flask and Jinja2. The reason behind this decision is primarily due to the limitations of Jinja2's developer experience and the fact that Python is not typed by default ...

A guide to resetting items directly from a dropdown select menu

I need help with clearing or resetting select options directly from the dropdown itself, without relying on an external button or the allowClear feature. Imagine if clicking a trash icon in the select option could reset all values: https://i.stack.imgur. ...

Guide on changing the content type of a Response header in a Next.js API route

I am currently working on a Next.js 14 app router and have a requirement to dynamically create an XML file when the API route is called and send it in response. Below is my code snippet: export async function GET(req: NextApiRequest, res: NextApiResponse) ...

SWR NextJS error remains unhandled despite being thrown

I'm struggling to manage errors thrown in my SWR fetcher. Currently, whenever an error is thrown, my app stops working and I see an "Unhandled Runtime Error". What I've been doing is throwing the error inside the fetcher function. Here's th ...

What causes the index to display [object Object] rather than an integer in React?

It has been a long time since I last worked with React, and now I'm facing an issue. Whenever I use console.log to display the index within the map function, my console output looks like this: https://i.stack.imgur.com/VbGmE.png However, the result ...

Guide on integrating msw with Next.js version 13.2.1 (Issue: Unable to access worker.start on the server)

I'm currently in the process of integrating a simulated API that sends back a response object containing a series of messages meant to be displayed in the UI (specifically, a chatbox) alongside the username, user picture, and other relevant informatio ...

What's the deal with session-based middleware?

In the way my architecture is structured: I have Next.js (browser) connecting to Next.js (middleware), which then talks to a 3rd-party API. The middleware has the task of managing and storing users' access tokens. Currently, everything is functioni ...

How can I append a query parameter to the URL in NextJS?

My goal is to include a query parameter whenever I enter some text in an input field and press the ENTER key. However, I'm struggling to determine the correct placement for this query parameter to function properly. Essentially, I want my URL to show ...

Heroku failing to set cross-site cookie through the Set-Cookie Response Header

Despite working fine locally, I am facing issues with setting cookies on Heroku when making cross-site calls. This problem seems to be occurring specifically in Chrome and Safari, the two browsers I have tested so far. It could be due to either the cross-s ...

Execute JavaScript function on click event in NextJS

Is it possible to execute a JavaScript function on the client side without using addEventListener? This situation works with addEventListener. MyComponent.js import Script from 'next/script' export default function MyComponent({ props }) { ...

"Exploring the inner workings of the 'this' keyword in a next

I'm facing an issue where I am trying to invoke a method from an onClick event within a class component: export default class WhiteListOptions extends Component { triggerPurchase = async (buyQty) => { await this.props.purchaseFunction( ...

Cleaning up with useEffect in the newest version of React

Recently, I made the switch to using locomotive scroll with next.js. However, after upgrading to react v18, my clean up stage has suddenly stopped working. Can someone shed some light on why this might be happening? useEffect(() => { let scroll; import( ...

Upon commencing the project, an error arises with reactstrap when attempting to import the library

Issue with Error console in node_modules/reactstrap/lib/index.js: SyntaxError: Cannot use import statement outside a module at internalCompileFunction (node:internal/vm:73:18) at wrapSafe (node:internal/modules/cjs/loader:1176:20) ... Node.js v18. ...