简体   繁体   中英

What are the best practices to work with next.js and express.js and use sessions

for a few weeks now i've started a project using node.js and express.js , I've also added React objects in the front.

I developped a full session manager using express-session and connect-mongodb-session and it works great.

I have one thing left to add now to have everything set up : next.js . And here it gets a little more complicated to me.

My purpose is to have the same thing I have now but with a smooth transition between pages.


I started using the official example from git : https://github.com/zeit/next.js/tree/canary/examples/custom-server-express

Which is very nice. But the pages in /page are public ? Someone could access them by entering their adress, which is not very good because sessions should be completly waterproof.

My first solution is to call them random names so people can't access them directly, but it's not very neat ... And they could still workarround ... This would make me write somehing like this :

 server.get('/nice_name', (req, res) => { 
    console.log('loaded') return app.render(req, res, '/uoiuouiorlos_ugly_random_name', req.query) })

My other solution is to make a route for their adress and call (req,res,next) => next()

This could work but ... is it pretty ?

Another solution is to edit next.config.js and write : module.exports = { useFileSystemPublicRoutes: true, }

it works great but then every page is loading like they would normally do ... So what would be the point ?

const express = require('express')
const next = require('next')

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

console.log('page loaded')

app.prepare().then(() => {
const server = express()

server.get('/', (req, res) => {
    console.log('loaded')
    return app.render(req, res, '/1A', req.query)
})

server.get('/space2', (req, res) => {
    console.log('loaded')
    return app.render(req, res, '/2A', req.query)
})

server.get('*', (req, res) => {
    return handle(req, res)
})

server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
})
})

I'm a beginner using next, thank you in advance for your help !

for now redirecting to a page named 404.js if people try to access the actual page works fine

express.get('/', (req, res) => {
    return app.render(req, res, '/landing_page', req.query);
})

express.get('/landing_page', (req, res) => {
        return app.render(req, res, '/404', req.query)
    });

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