简体   繁体   中英

Change url to default page next.js

I tried to find how to change the default page path (when you access the server on the "/" path) but couldn't find anything. I have a structure in the pages directory in the form index/index.jsx and I want this page to be returned by default when accessing the server. I did not find a similar question on this forum, maybe someone will need your help, except me.

The way pages structure works in Next.js is very opiniated. If you need to send a file from a different pages structure when accessing / you would need to configure your own little express server.

See this link for official doc.

You would then have something like :

// Some code

if (pathname === '/') {
    app.render(req, res, '/index', query) // Or /index/index.jsx
}

// Some code

Also if you do not want to create your own express server, you could have an index.js that redirects to your index page with something like this :

import Router from 'next/router'

const Index = () => null

Index.getInitialProps = async ({ res }) => {
    if (res) {
        res.writeHead(302, {
            Location: `/index`
        })
        res.end()
    } 
    else
        Router.push(`/index`)

    return {}
}

export default Index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM