inside src/utils.ts
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
import { SignJWT, jwtVerify } from "jose";
import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";`
./src/utils.ts
Error:
× You're importing a component that needs next/headers. That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/getting-started/
│ react-essentials#server-components
│
│
╭─[D:ProjectsProgrammingsupermuslim-dashboard-nextjssrcutils.ts:2:1]
2 │ import { twMerge } from "tailwind-merge";
3 │ import { SignJWT, jwtVerify } from "jose";
4 │ import { NextRequest, NextResponse } from "next/server";
5 │ import { cookies } from "next/headers";
· ───────────────────────────────────────
This is my src directory tree
│ middleware.ts
│ utils.ts
│
├───app
│ │ favicon.ico
│ │ globals.css
│ │ layout.tsx
│ │ page.tsx
│ │
│ ├───(auth)
│ │ │ layout.tsx
│ │ │
│ │ └───signin
│ │ page.tsx
│ │
│ └───dashboard
│ page.tsx
│
├───components
│ │ ModeToggle.tsx
│ │ Navbar.tsx
│ │
│ ├───Forms
│ │ LogInForm.tsx
│ │ RememberMeCheckbox.tsx
│ │ SignUpForm.tsx
│ │
│ └───ui
│ button.tsx
│ checkbox.tsx
│ dropdown-menu.tsx
│ form.tsx
│ input.tsx
│ label.tsx
│ toast.tsx
│ toaster.tsx
│ use-toast.ts
│
├───interfaces
│ index.ts
│
├───providers
│ theme-provider.tsx
│
└───server-actions
└───auth
actions.ts
There’s a function inside utils.ts
that is invoked on every request through middleware.ts
. I’m unable to identify the root cause of the error. My implementation is similar to the code in this repository:
https://github.com/balazsorban44/auth-poc-next/blob/main/lib.ts
2
Answers
Below is my layout.tsx for my wallet connect project where I need to pass headers in my context provider. Please consider this example.
It’s just an example, how you can pass headers in root layout. Let me know if this works for you or not.
The doc doesn’t seem to mention the use of the
cookies()
function in a middleware (even tough it’s not a “don’t”):Also, on the middleware doc, they don’t use the
cookies()
function, but rather the request itself: