Optimal method for saving authenticated user in redux state

I am currently working on developing an application with the following technologies:

  • Next.js
  • An Express API
  • Redux-Toolkit and RTK Query

All of the authentication logic has been implemented successfully, but I have encountered a problem.

After a successful login, the Express API sends back two httponly cookies containing the access and refresh tokens.

In my API, there is an endpoint to retrieve the current user using the access token, located at /api/auth/me

Everything is functioning properly. However, I am struggling to determine the best approach to fetch the user on each page load and store them in the Redux state.

Should I utilize RTK Query to call the /api/auth/me endpoint and invoke the query whenever needed across the application?

Ideally, I would like to fetch and set the user in _app.tsx, but I am unable to use Redux dispatch since it falls outside of the

<Provider store={store}></Provider>

For example, if I wanted to access the user stored in Redux in getServerSideProps, I am unable to do so as it is not client-side and does not have access to Redux.

I am facing difficulty in finding an efficient method to simply set the authenticated user and utilize them globally within the application, whether it be inside the Redux store or in scenarios like getServerSideProps.

Any guidance or suggestions would be greatly appreciated as I am feeling quite disoriented at the moment.

Answer №1

To maintain authentication state, one method is to save the token in local storage. Within the main App component, you can verify if the token exists in the redux store. If it is not found, you can manually set it using the useEffect function.

For example:

useEffect(() => {
fetchAuthTokenFromLocalStorage().then((token) => {
  dispatch(setAuthenticationResult(token));
});},[dispatch]);

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

The svh/lvh units are experiencing unexpected issues when using Chrome on an iPhone

I'm facing an issue with my hero section that is supposed to take up the full height of the viewport. I recently tried using the new svh/lvh units, which seemed to work fine on desktop and Safari for mobile. However, when testing on Chrome for mobile ...

Creating a menu that is even more optimized for mobile devices

I recently came across a mobile menu style that I really like: https://www.w3schools.com/html/default.asp What I appreciate about this style is that even on smaller screens, it still displays some main navigation items. This allows for popular links to be ...

Tips on incorporating several class names into Next.js elements

My current challenge involves an unordered list element with the following structure: <ul className={styles["projects-pd-subdetails-list"]}> {detail.subdetails.map((sub) => ( <li className={styles[ ...

CSS file not loading in an ExpressJS application

I'm facing an issue with my ExpressJS web app where only the HTML files are loading but the CSS rules are not being applied. I have linked the HTML file with the CSS file and also included express.static(path.join(__dirname, 'css')) in my ap ...

What causes TypeScript to interpret an API call as a module and impact CSS? Encountering a Next.js compilation error

My website development process hit a roadblock when I tried integrating Material Tailwind into my project alongside Next.js, Typescript, and Tailwind CSS. The compilation error that popped up seemed unrelated to the changes, leaving me baffled as to what c ...

display the information stored within the sports attribute using React

I am attempting to display the values stored in the sports property. So, I inserted a console log within the sports property. However, an error is being thrown: Syntax error: C:/codebase/src/containers/sports.js: Unexpected token, expec ...

Having troubles with Navbar svg images not loading on certain pages on the express/ejs app?

Hello there, I'm encountering an issue with my navbar in an express app. The navbar is saved as a partial and included in a boilerplate wrapper used on most pages. Here's a snippet of how it looks: <h1>HELLO<h1> Within the boilerplat ...

I am encountering difficulties displaying the image and CSS files from another folder in my HTML with Node.js

I am facing difficulty in establishing a connection between my front-end and back-end using node.js. As a result, the website only displays the HTML code without linking to the CSS or image files. Here is the folder structure: root -src •pi ...

Next.js is causing me some trouble by adding an unnecessary top margin in my index.js file

I started a new project using next.js by running the command: yarn create next-app However, I noticed that all heading and paragraph tags in my code have default top margins in next.js. index.js import React, { Component } from "react"; import ...

Changing the color of tabs using inline styles in material ui does not seem to work

I am brand new to using material ui and have been attempting to alter the colors of the selected tab. Currently, the color is a dark blue shade and I am aiming to change it to red. I tried applying inline styles, but unfortunately, there was no change. C ...

Adjust the loading bar component in Material UI to allow for customizable color changes

I am currently learning how to use material ui. My goal is to customize the loading bar's CSS. I checked the documentation and utilized colorPrimary classes. However, the changes are not appearing as expected. Could you please guide me on how to resol ...

What is the best way to load my CSS file using express.static?

How do I properly load my CSS file using express.static in Node.js? I have attempted various methods to link my stylesheet to my HTML file through Express, and I'm also interested in learning how to include images, JavaScript, and other assets to crea ...

Adjust Sidebar Height to Match Document Height (using React Pro Sidebar)

Having an issue with the height of a sidebar component in Next.js using React Pro Sidebar. It seems to be a JavaScript, HTML, and CSS related problem. I've tried several suggested solutions from Stack Overflow, but none of them seem to work. Surprisin ...

Image loading in NextJS is limited to only Firefox browsers

Images are loading only in Firefox and not anywhere else. Here is the import statement: import gradient from '../public/mountains/gradient.svg' And here is the Image component: <div id='gradient' className={`${styles.bgimage} ${sty ...

"Utilizing multiple class names in Next.js to enhance website styling

Looking for a way to apply multiple classNames in Next.js, especially when dealing with variable classnames? I'm following the component level CSS approach. Take a look at my code and what I aim to achieve: import styles from "./ColorGroup.mod ...

Modify the font style of numbers based on the keyboard language selected by the user

Is it possible to change the font family of numbers in input fields based on the user's keyboard language? For example, if the user is typing in Persian, the numbers should be displayed in a Persian font, and when they switch to an English keyboard, t ...

React NextJS CSS - Setting the section's height to 100% of the parent's height results in taking up 100% of the page's height

I've encountered an issue while transferring my project to NextJS from Create-React-App. In NextJS, setting the height of a section to 100% is causing it to take up the entire page height instead of adjusting for the header and footer elements. I nee ...

Include a class for CSS styling in EJS using Node.js

Attention: Please be aware of the environment in this Application. The following technologies are being used: Windows NPM, Express MySQL This is the code in an ejs template called example.ejs <% if (message) { %> <p class="al ...

A guide to replacing or customizing standard components in ReactJS

I need to modify the color property of a common component so I can use it elsewhere. const ViewAllIcon = (props) => ( <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 26 ...

Is there a way to remove the scrollbar from the menu created with react-burger-menu?

How can I remove the scroll bar from the menu created with react-burger-menu? Despite trying various CSS properties adjustments, I have not been able to achieve the desired effect. Here is an image of the open menu and the corresponding CSS: (https://i.st ...