I have recently started a project where I am trying to create a social media website which renders the users’ posts and users can comment on them. I am using Nextjs 14 and am using the app route. Instead of sending my complex project, I will include a simple example, so please ignore styling and formatting.
Root page.tsx – includes the title of the page and a button that redirects to the homepage
Home route – page.tsx – includes the title of the page and a button that opens the modal. When the modal is open the url changes to /compose/post
@modal/(.)/compose/post – page.tsx – includes the title of the modal and the close button that redirects the user back to the home page.
At the moment it all works okay. The only issue is that when I refresh the page when the modal is open (/compose/post), then the page renders a 404. I think this is related to adding a default.tsx page that returns null. I have done this, but it is still not working.
Can anyone point me in the right direction?
This is my file structure
src/
app/
@modal/
default.tsx
.(compose)/
post/
page.tsx
default.tsx
home/
page.tsx
default.tsx
globals.css
layout.tsx
page.tsx
Here is the Github link.
Here is the code for each file that is relevant:
//src/app/page.tsx
"use client";
import { useRouter } from "next/navigation";
export default function Home() {
const router = useRouter();
const handleOnClick = () => {
router.push("home");
};
return (
<>
<div>I am the root page</div>
<button style={{ background: "blue" }} onClick={handleOnClick}>
Go to homepage
</button>
</>
);
}
//src/app/layout.tsx
import type { Metadata } from "next";
import { Inter } from "next/font/google";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Intercepting and Parallel Routes",
description: "Experimenting",
};
export default function RootLayout({
children,
modal,
}: {
children: React.ReactNode;
modal: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>
{modal}
{children}
</body>
</html>
);
}
//src/app/default.tsx
import Page from "./page";
export default Page;
//src/app/home/page.tsx
"use client";
import { useRouter } from "next/navigation";
export default function Home() {
const router = useRouter();
const handleOnClick = () => {
router.push("compose/post");
};
return(
<>
<div>I am the homepage</div>
<button style={{ background: "blue" }} onClick={handleOnClick}>
Open modal
</button>
</>
)
}
//src/app/@modal/page.tsx
export default function Page() {
return null;
}
//src/app/@modal/default.tsx
export default function Default() {
return null;
}
//src/app/@modal/(.)compose/post/page.tsx
"use client";
import { useRouter } from 'next/navigation';
export default function ComposePost() {
const router = useRouter();
const handleClose = () => {
router.back();
};
return(
<>
<div>I am the modal</div>
<button style={{background: 'green'}}onClick={handleClose}>Close</button>
</>
)
}