Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  2] [ 1]  / answers: 1 / hits: 41105  / 6 Years ago, thu, july 19, 2018, 12:00:00

I'm trying to figure out an appropriate way of doing authentication, which I know is a touchy subject on the GitHub issue page.



My authentication is simple. I store a JWT token in the session. I send it to a different server for approval. If I get back true, we keep going, if I get back false, it clears the session and puts sends them to the main page.



In my server.js file I have the following (note- I am using the example from nextjs learn and just adding isAuthenticated):



function isAuthenticated(req, res, next) {
//checks go here

//if (req.user.authenticated)
// return next();

// IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM SOMEWHERE
res.redirect('/');
}

server.get('/p/:id', isAuthenticated, (req, res) => {
const actualPage = '/post'
const queryParams = { id: req.params.id }
app.render(req, res, actualPage, queryParams)
})


This works as designed. If I refresh the page /p/123, it will redirect to the /. However, if I go there via a next/link href, it doesn't. Which I believe is because it's not using express at this point but next's custom routing.



Is there a way I can bake in a check for every single next/link that doesn't go through express so that I can make sure the user is logged in?


More From » reactjs

 Answers
4

Tim from the next chat helped me solve this. Solution can be found here but I will quote him so you all can see:



I've also created an example skeleton template you can take a look at.


--



EDIT July 2021 - WARNING: This is an outdated solution and has not been confirmed to work with the latest versions of next.js. Use skeleton template at your own risk.



[#53935] Tuesday, July 17, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harveys

Total Points: 113
Total Questions: 88
Total Answers: 79

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
;