Next.js error with import async function
Answered
Challangerson posted this in #help-forum
the error
async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server.Answered by Asian black bear
Your login page is a client component and renders
<GalleryPage /> which is an async component. The error clearly tells you that you cannot have async components in client components/pages.11 Replies
login/page.jsx
'use client'
import React from 'react'
import { useQueryState } from 'nuqs'
import { useState, useEffect } from "react";
import GalleryPage from '../galleryPage/page';
function page() {
const [name, setName] = useQueryState('password');
const [isAuthorized, setIsAuthorized] = useState(false);
useEffect(() => {
// Check if the password matches
if (name === "123") {
setIsAuthorized(true); // Grant access to the page
} else {
// Redirect back to the previous page if unauthorized
window.open("/", "_self");
}
}, [name]);
if (!isAuthorized) return null;
return (
<div>
<h1>Pgotos!</h1>
<GalleryPage />
</div>
)
}
export default pagegalleryPage/page
import Image from 'next/image';
import path from 'path';
import { promises as fs } from 'fs';
const GalleryPage = async () => {
const imageDirectory = path.join(process.cwd(), 'public/memories');
const imageFilenames = await fs.readdir(imageDirectory); // Fetch image file names on the server
return (
<div className="gallery">
<div className="images">
<Gallery images={imageFilenames} />
</div>
</div>
);
};
const Gallery = ({ images }: { images: Array<string> }) => {
return (
<div className="grid">
{images.map((el) => (
<Image
className="card"
width={150}
height={150}
alt="alt"
src={`/memories/${el}`}
key={el}
/>
))}
</div>
);
};
export default GalleryPage;app directory
wanna more information, ask!
Asian black bear
Your login page is a client component and renders
<GalleryPage /> which is an async component. The error clearly tells you that you cannot have async components in client components/pages.Answer
so how can i fix it
fs.readdir need fsync
Asian black bear
You rewrite your "auth" check to work server-side without a hook.
Pages receive the search params as an argument and you can redirect using the
redirect function from Next.