#Routes as static pages to take advantage of Next Navigation
1 messages · Page 1 of 1 (latest)
Hi @short shoal. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To refactor your app to build non-API routes as static pages, you can use Next.js's static rendering capabilities. This involves using the getStaticProps function to fetch data at build time, which is then used to generate static HTML pages.
Here's an example of how you can use getStaticProps to fetch data directly from a database or another source, without making an API call:
// pages/blog.js
import { loadPosts } from '../lib/load-posts'
// This function runs only on the server side
export async function getStaticProps() {
// Instead of fetching your `/api` route you can call the same
// function directly in `getStaticProps`
const posts = await loadPosts()
// Props returned will be passed to the page component
return { props: { posts } }
}
In this example, loadPosts is a function that fetches data directly from a CMS or another source. This function is shared with getStaticProps and API routes from a lib/ directory. This way, you can avoid making an additional API call and improve performance (source (https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-props)).
To generate a static export of your Next.js app, you can run next build. This will generate an HTML file for each route, which can be served by any web server that can serve HTML/CSS/JS static assets. Here's how you can configure your next.config.js to enable a static export:
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
output: 'export',
// Optional: Change links `/me` -> `/me/` and emit `/me.html` -> `/me/index.html`
// trailingSlash: true,
// Optional: Prevent automatic `/me` -> `/me/`, instead preserve `href`
// skipTrailingSlashRedirect: true,
// Optional: Change the output directory `out` -> `dist`
// distDir: 'dist',
}
module.exports = nextConfig
After running next build, Next.js will produce an out folder which contains the HTML/CSS/JS assets for your application (source (https://nextjs.org/docs/pages/building-your-application/deploying/static-exports)).