안녕하세요, app router에 대해 계속 공부하다가 route handlers 에 대한 궁금증이 해결되지 않아 질문하게 됐습니다. Next app router에서 정확히 route handlers를 사용해야 하는 이유가 무엇인가요? 제가 생각했을 땐 서버 데이터 캐싱이나 API 엔드포인트를 숨길 수 있다는 장점이 있는데 이건 서버 컴포넌트에서 fetch하는 것으로도 대체가 되는데 route handlers를 사용해야 하는 특별한 이유가 따로 있는 것인가요? 모든 API를 route handlers로 하면 Next서버에 부하가 걸릴텐데 어떻게 해결할 수 있을까요? 이 부분은 공식문서에서 제가 못 찾은 것 같은데, 만약 외부 백엔드 API가 있고 여기에 데이터 요청을 할 때 클라이언트 컴포넌트에서의 모든 API 요청을 1차로 route handler에 하고 여기서 외부 백엔드 API로 요청하게되면 route handlers에 요청이 몰리게 되는데 이때 Next 서버에 걸리는 부하를 어떻게 해소할 수 있을까요?
제로초님 하신대로 그대로 프로젝트를 생성하고 실행했더니 화면은 그대로 뜨는데 에러가 1개 있어서 봤더니 hydration 에러라고 뜨네요 ㅠㅠ 지금 z-com 프로젝트를 수업용 / 연습용으로 총 2개 진행중인데 수업용 프로젝트는 이런 에러가 없었는데 연습용에서 에러가 발생하네요. 아래는 에러 코드입니다 ! Console Error Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used - A server/client branch if (typeof window !== 'undefined') . - Variable input such as Date.now() or Math.random() which changes each time it's called. - Date formatting in a user's locale which doesn't match the server. - External changing data without sending a snapshot of it along with the HTML. - Invalid HTML tag nesting. It can also happen if the client has a browser extension installed which messes with the HTML before React loaded
안녕하세요 nextjs를 활용해서 프로젝트를 진행하는 중에 해결되지 않는 문제가 발생하여 질문 드립니다. 현재 도커를 활용해서 nextjs를 배포하고 있는데 middleware에서 request.nextUrl.origin값이 https://localhost:3000이 들어가고 있습니다. x-forwarded-host를 찍었을때는 제가 사용하는 https://test.domain.com이 들어가는데 request.nextUrl.origin에 x-forwared-host와 같은 값이 들어가도록 설정하기 위한 방법이 있는지 알 수 있을까요??
안녕하세요 강의를 듣는중 추가적으로 tanstack-query를 공부하다가 혼자서 도저히 이해를 할수 없는 부분이 있어서 이 부분에 대해 혹시 조언을 받을수 있을까 싶어 문의드립니다. prefetchQuery가 개인적으로 잘 이해가 안되어서 별도로 프로젝트를 생성하여 기본적인 것부터 다시 공부하고 있었습니다만, tanstack-query 공식사이트에서 권장하던 방법대로 임의적으로 코드를 생성하였더니 router.push()로 다른 페이지에 갔다가(->홈으로[/]) 다시 돌아오는것(->Post페이지(/post))을 반복하다보면 가끔 서버 컴포넌트에 있는 prefetchQuery안의 fetch와 클라이언트 컴포넌트에 있는 useQuery의 fetch가 동시에 실행이 되는 일이 가끔 발생을 해서요. fetch가 이중으로 실행이 되고 있는것 같은데 아무리 코드를 살펴봐도 제가 잘못한 부분을 찾을수가 없어서 조언을 구합니다ㅠ page.tsx import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query'; import Post from './_component/Post'; import getPostRecommends from './_hook/fetch'; export default async function tanstackQuery() { const queryClient = new QueryClient(); await queryClient.prefetchQuery({ queryKey: ['movies'], queryFn: getPostRecommends, }); const dehydratedState = dehydrate(queryClient); return ( <HydrationBoundary state={dehydratedState}> <Post /> </HydrationBoundary> ); } post.tsx 'use client'; import { useQuery } from '@tanstack/react-query'; import getPostRecommends from '../_hook/fetch'; import { useRouter } from 'next/navigation'; export default function TanstackQuery() { const { data } = useQuery({ queryKey: ['movies'], queryFn: getPostRecommends, }); const router = useRouter(); type PostItem = { id: number; title: string; }; return ( <div> <button onClick={() => router.push('/')}>홈으로</button> {data?.map((item: PostItem) => { return ( <div key={item.id}> <h2>{item.title}</h2> </div> ); })} {data?.message} </div> ); } getPostRecommends export default async function getPostRecommends() { if (typeof window === 'undefined') { console.log('서버에서 fetch 실행' + new Date()); } else { console.log('클라이언트에서 fetch 실행' + new Date()); } const response = await fetch('https://jsonplaceholder.typicode.com/posts?_page=1&_limit=10', { cache: 'no-store', }); if (!response.ok) { throw new Error('Failed to fetch data'); } const res = await response.json(); return res; } 기본 provider 설정 'use client'; import { isServer, QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { ReactNode } from 'react'; import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; function makeQueryClient() { return new QueryClient({ defaultOptions: { queries: { staleTime: 6 * 1000, }, }, }); } type Props = { children: ReactNode }; let browserQueryClient: QueryClient | undefined = undefined; function getQueryClient() { if (isServer) { return makeQueryClient(); } else { if (!browserQueryClient) browserQueryClient = makeQueryClient(); return browserQueryClient; } } export default function Providers({ children }: Props) { const queryClient = getQueryClient(); return ( <QueryClientProvider client={queryClient}> {children} <ReactQueryDevtools /> </QueryClientProvider> ); } 서버 콘솔 브라우저 콘솔 위에 캡쳐화면 같이 fetch가 거의 동시간에 발생을 하고 있는 모습입니다. next.js router cache 때문에 30초마다 서버 컴포넌트쪽이 리랜더링 되어서 페이지를 새로고침을 하지 않고 router.push로 다시 페이지에 들어가도 서버 컴포넌트쪽이 다시 실행된다는건 이해를 했는데, 그렇다면 초기 랜더링할때와 똑같이 데이터가 prefetch되어서 클라이언트쪽 useQuery가 실행이 되지 않아야하지 않나요? 왜 두번이나 fetch가 도는건지 아무리 자료를 찾아봐도 잘 모르겠어서 결국 문의드리게 되었습니다ㅠ
[섹션4-4 클라이언트 컴포넌트에서 ServerActions 사용하기] 제가 사용하고있는 라이브러리 버전입니다. "next": "^15.0.0-canary.181", "next-auth": "^5.0.0-beta.22", "react": "^18", "react-dom": "^18" useFormState 현재 공식문서 에선 useFormState from 'react-dom' 이 아닌 useActionState from 'react` 로 사용하도록 되어있더라구요. 그래서 해당 변경사항대로 사용해도 문제가 없을지 궁금합니다. useFormStatus 공식문서 를 읽어보는데 " useFormStatus 는 동일한 컴포넌트에서 렌더링한 <form> 에 대한 상태 정보를 반환하지 않습니다." 라고 명시가 되어있더라구요. 그런데 현재 제로초님의 코드는 동일한 컴포넌트의 form에 대해서 pending 값을 받고 있는데, 문제가 발생하지 않는 이유에 대해서 궁금합니다.
전공자따라잡기 데이터베이스 공부중에 mysql 대신 이 강의 할때 깔았던 postgreSQL로 연습해보려고 하다가 질문드립니다 서버그룹 우클릭 -> register -> server 하면 사용자 이름으로 된 기본db와 함께 zcom이 항상 같이 생성되는데 이 zcom db 생성안되게 하려면 어떻게 해야하나요?
login 시 let setCookie = response.headers.get('Set-Cookie'); 가져오려고 할 때 response.headers에는 뜨는데 samesite 때문에 cookie를 가져올 수 없습니다. 개발자도구에서 samesite 에러 어떻게 해결할 수 있을까요?? 아래와 같이 수정했는데 같은 오류가 발생합니다. if (setCookie) { const parsed = cookies.parse(setCookie); cookies().set('connect.sid', parsed['connect.sid'], { sameSite: 'None', secure: true }); }
안녕하세요 제로초님. 강의 잘 보고 있습니다. <img src={ photo.link } alt={ photo.Post ?.content} /> <div className={style.image} style={{backgroundImage: `url(${ photo.link })`}} /> 여기서 css를 보니 img에 display none을 주고 div에 style의 bg로 이미지를 주셨던데 왜 이렇게 하신건지 특별한 이유가 있나요? 궁금합니다.
병렬 라우팅에 문제가 있는 거 같아 문의 드립니다. 강의 그대로 패러렐 라우트, 인터셉터 라우트까지 모두 따라했었는데, "Application error: a client-side exception has occurred (see the browser console for more information)." 브라우저에 이런 에러가 뜨면서, 콘솔창에는 아래와 같이 에러가 뜨더라구요. app-index.js:33 Warning: Cannot update a component (`HotReload`) while rendering a different component (`Router`). To locate the bad setState() call inside Router , follow the stack trace as described in https://reactjs.org/link/setstate-in-render at Router (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js:207:11) at ErrorBoundaryHandler (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:113:9) at ErrorBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:160:11) at AppRouter (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js:585:13) at ServerRoot (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/app-index.js:112:27) at Root (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/app-index.js:117:11) window.console.error @ app-index.js:33 Show 1 more frame Show lessUnderstand this error react-dom.development.js:9126 Uncaught TypeError: initialTree is not iterable at applyPatch (apply-router-state-patch-to-tree.js:17:53) at applyRouterStatePatchToTree (apply-router-state-patch-to-tree.js:74:30) at applyRouterStatePatchToTree (apply-router-state-patch-to-tree.js:76:30) at eval (navigate-reducer.js:142:88)Understand this error app-index.js:33 The above error occurred in the <Router> component: at Router (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js:207:11) at ErrorBoundaryHandler (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:113:9) at ErrorBoundary (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/error-boundary.js:160:11) at AppRouter (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js:585:13) at ServerRoot (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/app-index.js:112:27) at Root (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/app-index.js:117:11) React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundaryHandler. 그래서 어디서 난 에러인지 추리려고 인터셉터 라우트 부분은 아예 빼버리고, 패러랠 라우트 부분으로 확인해보는데, 패러랠 라우트 부분부터 아예 에러가 나서 이것이 문제인 거 같더라구요. { "name": "z-com", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "classnames": "^2.5.1", "dayjs": "^1.11.13", "next": "14.2.11", "react": "^18", "react-dom": "^18" }, "devDependencies": { "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", "autoprefixer": "^10.4.20", "eslint": "^8", "eslint-config-next": "14.2.11", "postcss": "^8.4.47", "tailwindcss": "^3.4.12", "typescript": "^5" } } package.json과 디렉토리 구조는 이런 상태이구요. @modal/compose/tweet/page.tsx @modal/compose/tweet/modal.module.css @modal/default.tsx 이 세 파일은 깃헙 ch2-2 에 나온대로 그대로 적었습니다. import {ReactNode} from "react"; import style from '@/app/(afterLogin)/layout.module.css'; import Link from "next/link"; import Image from "next/image"; import ZLogo from '../../../public/zlogo.png'; import NavMenu from "@/app/(afterLogin)/_component/NavMenu"; import LogoutButton from "@/app/(afterLogin)/_component/LogoutButton"; import TrendSection from "@/app/(afterLogin)/_component/TrendSection"; import FollowRecommend from "@/app/(afterLogin)/_component/FollowRecommend"; // import RightSearchZone from "@/app/(afterLogin)/_component/RightSearchZone"; type Props = { children: ReactNode, modal: ReactNode } export default function AfterLoginLayout({ children, modal }: Props) { return ( <div className={style.container}> <header className={style.leftSectionWrapper}> <section className={style.leftSection}> <div className={style.leftSectionFixed}> <Link className={style.logo} href="/home"> <div className={style.logoPill}> <Image src={ZLogo} alt="z.com로고" width={40} height={40} /> </div> </Link> <nav> <ul> <NavMenu /> </ul> <Link href="/compose/tweet" className={style.postButton}> <span>게시하기dd</span> {/* <svg viewBox="0 0 24 24" aria-hidden="true" className="r-jwli3a r-4qtqp9 r-yyyyoo r-1472mwg r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-lrsllp"><g><path d="M23 3c-6.62-.1-10.38 2.421-13.05 6.03C7.29 12.61 6 17.331 6 22h2c0-1.007.07-2.012.19-3H12c4.1 0 7.48-3.082 7.94-7.054C22.79 10.147 23.17 6.359 23 3zm-7 8h-1.5v2H16c.63-.016 1.2-.08 1.72-.188C16.95 15.24 14.68 17 12 17H8.55c.57-2.512 1.57-4.851 3-6.78 2.16-2.912 5.29-4.911 9.45-5.187C20.95 8.079 19.9 11 16 11zM4 9V6H1V4h3V1h2v3h3v2H6v3H4z"></path></g></svg> */} </Link> </nav> <LogoutButton /> </div> </section> </header> <div className={style.rightSectionWrapper}> <div className={style.rightSectionInner}> <main className={style.main}>{children}</main> <section className={style.rightSection}> {/* <RightSearchZone /> */} <TrendSection /> <div className={style.followRecommend}> <h3>팔로우 추천</h3> <FollowRecommend /> <FollowRecommend /> <FollowRecommend /> </div> </section> </div> </div> {modal} </div> ) } layout.tsx도 위에 코드와 같이 거의 그대로 적었구요. 참고로 layout.tsx에서 console.log(modal) 했을 때, undefined 뜹니다. 근데 또 explore로 이동한 뒤 게시하기 버튼을 누르면 modal이 뜹니다. 이것 저것 다해보다가 도저히 안풀려서 문의드립니다. 제가 어디서 놓친 걸까요...
안녕하세요 제로초님 강의를 듣다가 문득 궁금한점이 있어서 질문드립니다. 현재 폴더 구조가 app하위에 (afterLogin) 폴더와 (beforeLogin) 폴더가 있는데, 지금 강의에서는 당연한듯이 beforeLogin 폴더의 layout이 뜨고있는데요, 왜 그런건지 궁금합니다. 현재 단계에서는 뭔가 로그인을 했다는 조건같은걸 아직 작성하지 않은것 같아서요 정리하자면 현재 localhost:3000 의 기본 페이지가 afterlogin 폴더의 layout이 아니라 beforeloign의 layout이 뜨는 이유가 궁금합니다.
안녕하세요 강의 잘 보고 있습니다. 한가지 질문이 있는데요! 라우팅 테스트 중에 (beforeLogin) 하위로 추가 생성되는 라우트는 Link로 접속하면 잘 되는데, 직접 URL로 치고 가면 not-found 페이지가 뜨는데 어떤 이유일까요 ? 질문1) 아래 이미지의 itest 폴더 인터셉팅 잘됨. 하지만 새로고침 하거나 직접 localhost:3000/itest 치고 들어가면 페이지 없음. (원래는 새로고침 시 page.tsx 내용이 보여야 하지 않나요?) 질문2) 테스트겸 localhost:3000/dkwlsWK 라우트를 생성해서 직접 URL치고 들어가니 역시 없는 페이지로 뜹니다. 혹시 (그룹핑) 하거나 페레럴을 사용한 것과 연관이 있을까요 ? 질문3) 아래 이미지 중 @modal/(.)itest 에 default.tsx 로 하면 에러가 나더라구요! (page.tsx로 하면 괜찮지만 페이지를 찾을 수 없음)