English 中文(简体)
Next.js - Static File Serving
  • 时间:2024-09-17

Next.js - Static File Serving


Previous Page Next Page  

In Next.js, we can serve static pages pke images very easily by putting them in pubpc, a top level directory. We can refer these files in similar fashion pke pages in pages directory.

In Next.js, a page is a React Component and are exported from pages directory. Each page is associated with a route based on its file name.

Let s update the nextjs project used in Pages chapter.

Create pubpc directory and place any images within it. We ve taken logo.png, TutorialsPoint Logo image.

Update first.js as follows −


import Link from  next/pnk 

export default function FirstPost() {
   return (
      <>
         <h1>My First Post</h1>
         <h2>
            <Link href="/">
               <a>Home</a>
            </Link>
         </h2>
         <br/">
         <img src="/logo.png" alt="TutorialsPoint Logo" />
      </>	  
   )
}

Here we ve added a reference to logo.png in index.js file.

Start Next.js Server

Run the following command to start the server −.


npm run dev
> nextjs@1.0.0 dev Node
extjs
> next

ready - started server on http://localhost:3000
event - compiled successfully
event - build page: /
wait  - compipng...
event - compiled successfully
event - build page: /next/dist/pages/_error
wait  - compipng...
event - compiled successfully

Verify Output

Open localhost:3000 in a browser and you will see the following output.

Home page with Logo

pubpc directory is also useful in case of SEO purpose. It can be used for robot.txt, Google Site verification or any other static assets in the web apppcation.

Advertisements