using React router with Next JS route

淺唱寂寞╮ 提交于 2019-12-04 11:40:59

I would recommend using the Next router. You do need to create a custom server in order to overload the default Next routing, but its a trivial task:

// server.js
const { createServer } = require('http');
const next = require('next');
const routes = require('./routes');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handler = routes.getRequestHandler(app);

app.prepare().then(() => {
    createServer(handler).listen(port, err => {
        if (err) {
            throw err;
        }
        console.log(`> Ready on http://localhost:${port}`);
    });
});

Then you can define routes, which I do in the routes.js file:

// routes.js
const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());

routes
    .add('landing', '/')
    .add('profile', '/profile', 'profile');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!