Exploring the process of retrieving cookies on both the client and server side with Next.js 13

One of the functionalities in my code is a custom function called myFetch, which serves as a wrapper for fetch to include a token in the header.

import clientCookies from "js-cookie";
import {cookies} from "next/headers";

const myFetchedData = async (...args) => {
let token
if (typeof window === "undefined") {
  // When running on the client side
  token = clientCookies.get("authToken")
} else {
  // When running on the server side
  serverCookies = cookies()
  token = serverCookies.get("authToken").value
}

args[1].headers = {"Authorization": `bearer ${token}`}
const response = await fetch(...args)
const information = await response.json()
return information
}

However, I encountered an error when using this function on the client side.

You're trying to import a component that requires next/headers, which only functions within a Server Component. But one of its parent components is assigned with "use client", making it a Client Component.
For more information, visit: https://nextjs.org/docs/getting-started/react-essentials

I am seeking guidance on how to specifically "import {cookies} from 'next/headers'" exclusively for server-side purposes.

Answer №1

To dynamically import modules based on the type of the window object, you can conditionally import each module. If the window object is undefined, import the server module; otherwise, import the client module:

const myAsyncFunction = async (...args) => {
  let authToken;
  if (typeof window === "undefined") {
    const { cookies: serverCookies } = await import("next/headers");
    authToken = serverCookies().get("authToken").value;
  } else {
    const { default: clientCookies } = await import("js-cookie");
    authToken = clientCookies.get("authToken");
  }

  args[1].headers = { Authorization: `bearer ${authToken}` };
  const response = await fetch(...args);
  const responseData = await response.json();
  return responseData;
};

Answer №2

- (axios/client-axios.ts): Configuring Axios for client-side requests.
- (axios/server-axios.ts): Setting up Axios for server-side interactions.
- (axios/index.ts) :Dynamically selecting the appropriate Axios configuration based on the environment.
// axios/client-axios.ts
import axios, {
  AxiosInstance
}
from "axios";
import {
  API_BASE_URL
} from "../../lib/constant";
import {
  getCookie
} from "cookies-next";

const clientAxiosInstance: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    Authorization: `Bearer ${getCookie("accessToken")}`,
  },
});

export default clientAxiosInstance;

// axios/server-axios.ts
import axios, {
  AxiosInstance
} from "axios";
import {
  API_BASE_URL
} from "../../lib/constant";
import {
  cookies
} from "next/headers";

const serverAxiosInstance: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    Authorization: `Bearer ${cookies().get("accessToken")?.value}`,
  },
});

export default serverAxiosInstance;

// axios/index.ts
import {
  AxiosInstance
} from "axios";
let axiosInstance: AxiosInstance;

if (typeof window === "undefined") {
  axiosInstance = require("@/config/axios/server-axios").default;
} else {
  axiosInstance = require("@/config/axios/client-axios").default;
}

export default axiosInstance;

// example-usage
import axios from "@/config/axios";

axios.get("https://example.com/api/data").then((response) => {
  console.log(response.data);
});

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

"Utilizing jQuery's getJSON method in a session to fetch data

I have a code snippet that fetches the current number of likes on Facebook like this: $(document).ready(function() { $.getJSON('https://graph.facebook.com/<username>?callback=?', function(data) { var fb_count = data['likes ...

Updating votes on the client side in WebForms can be achieved by following these steps

I am currently working on implementing a voting system similar to Stack Overflow's. Each item has a vote button next to it, and I have it functioning server side causing a delay in reloading the data. Here is the current flow: Clicking the vote butt ...

When I utilize axios to send the request, the express routes for creating a new JSON entry in the mongo collection function correctly

Currently, I am working on building a course registration system that utilizes a form to send student data to a database. I have successfully created Express routes to add new entries to a mongo collection through a post request. Everything functions as ex ...

Internet Explorer 9 encountered a JavaScript error: SCRIPT5007. It was unable to access the value of the property 'ui' because the object is null or undefined

My website is functioning properly on Chrome, Firefox, and Internet Explorer 8. However, when it comes to Internet Explorer 9, some strange errors occur just by hovering over elements. SCRIPT5007: Unable to retrieve the value of the property 'ui&ap ...

NextJS encounters an 'ER_NOT_SUPPORTED_AUTH_MODE' error when attempting to establish a MySQL connection initialization through Environment Variables

My attempt to retrieve data from a MySQL table was successful when I hardcoded the configuration. However, when I tried using environment variables for configuration, I encountered the following error: code: 'ER_NOT_SUPPORTED_AUTH_MODE', errn ...

"Exciting features of NextJS 13 include the utilization of client component callback functions

Let's say I need to develop a custom Table React component with server-side pagination and sorting features, which can be reused in different parts of the application to display various types of data. In my create-react-app project, I would create a ...

Issues encountered with executing `npm run dev`

Encountering an issue with vueJs webpack while trying to run it on the server using the command: npm run dev. Unfortunately, an error message keeps popping up. Can anyone offer guidance on how to resolve this issue? Your help is greatly appreciated! Erro ...

Issues encountered in loading JavaScript with jQuery script

I am facing an issue with my jQuery script not loading correctly. When I click on the calculate button, nothing happens as expected. I made sure to copy and paste jQuery directly into the file for offline use, and also created a personal console due to res ...

Tips on dynamically passing parameters in Angular's $resource

Is there a way to dynamically pass a default parameter value in $resource? Take a look at the Plunker for reference. In the code snippet below, I've set the default parameter in the factory as: app.factory('myFactory', ["$resource", functio ...

Store data retrieved in Next.js' getServerSideProps so that it can be accessed throughout the application without the need to continuously reload it each time the page is

I'm working on an index page where I fetch data using getServerSideProps. If I navigate to other pages using next/link or router.push(), is there a way for the fetched data to persist across all pages in my application? Or do I need to consider usin ...

AngularJS directive for Ionic Leaflet - Utilizing Service to switch tileLayer from side menu

I am currently experimenting with developing an ionic app for the leaflet-angularjs-directive. Unfortunately, there are not many demos available for me to test out. The specific demo I am using is called ionic-leafletjs-map-demo by calendee on GitHub whic ...

Ways to convert field data to lowercase in MongoDB query result

I have two Objects in my database collection. [ {"_id" : 1, name: "notLowercased"}, {"_id" : 2, name: "lowercased"}, ] Using find and $regex to search for names that include a specific string. data = await Catal ...

Creating a Form with a Custom Format in AngularJS

Just starting out with AngularJS and currently working with ACTIVITI. I'm looking to create a form in a specific structure where each response follows this format: { "taskId" : "5", "properties" : [ { "id" : "room", ...

The conditional logic in AngularJS is not functioning as expected

https://i.sstatic.net/RvqYQ.pngMy code seems to have an issue with the if/else statement. I am checking the value of data.success which should contain either true or false. However, when I use (data.success === true) in the if statement, the else block e ...

Creating a Dynamic Bootstrap 4 Dropdown Menu using Jquery Hover

My Bootstrap Dropdown menu has a JQuery animation that is exactly what I want. However, when I move my cursor from the Dropdown's name (.dropdown) to an item in the dropdown, it starts acting erratically. $('.dropdown').hover(function() { ...

Error encountered while compiling a method within a .vue component due to a syntax issue

I have been closely following a tutorial on Vue.js app development from this link. The guide instructed me to add a login() function in the block of the Login.vue file. Here is the snippet of code provided: login() { fb.auth.signInWithEmailAndPa ...

Generating variable names dynamically in JavaScript

To prevent a javascript heap issue, I implement the usage of multiple arrays including 'family1', 'family2','family3' and 'dogs1', 'dogs2', 'dogs3'. For instance, you can use 'family1 and dog ...

Using the JQuery template with $.get function does not produce the desired result

Working on populating a table using a Jquery Template can be tricky. One challenge is incorporating a json file via an ajax call for the population process. $(document).ready(function() { var clientData; $.get("/webpro/webcad/lngetusuario", funct ...

I'm experiencing an issue where the changes I make in .aspx files are not showing up when I debug or rebuild

Recently, I have been experiencing an issue with my website where changes made to the .aspx file do not reflect when I debug or rebuild it. The only way for me to see the changes is by closing Visual Studio program and reopening the solution before debuggi ...

Calculate the total of all values associated with a dynamically generated key within an array of objects

I'm trying to calculate the sum of similar keys in an array of objects. Each object in the array will have some common keys, but not all arrays will share the same set of keys. I'm considering storing these keys in a separate array and then loopi ...