35

I'm developing a Next.JS app where a user should login to see the content.I want to redirect the user to '/' if their username and password are correct.However my implementation seems not working.

I searched on SO for questions regarding this,but all of them were talking about redirecting with getInitialProps but it doesn't help me since I want to redirect user from my custom express server.

Login.js

 async handleSubmit(event) {
  event.preventDefault()
  const { username, password } = this.state

  try {
    const response = await fetch('/log_in', {
      method: 'post',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password })
    })
  }

 catch (error) {
    console.log(error)
  }
}  

server.js

app.post('/log_in', (req,res) => {
    console.log(`login form data`);
    console.log(`Username : ${req.body.username}`);
    console.log(`password : ${req.body.password}`);
    if(req.body.username == "user" && req.body.password == "123"){
        res.redirect('/')
    }
}) 
0

3 Answers 3

77

This is now possible on Next.js 10+ without having to do any sort of response header manipulation directly. Use getServerSideProps or getStaticProps and return a redirect key as the only value from it if your conditions are met:

export async function getServerSideProps(context) {
  if(context.req.body.username == "user" && context.req.body.password == "123"){
    return {
      redirect: {
        permanent: false,
        destination: "/"
      }
    }
  }
}
2
  • 3
    Worth mentioning that for this to work Next also needs a default export of a page component. Eg, export default function Redirect() { }
    – rgdigi
    Jul 3, 2021 at 12:38
  • @rgdigi Good point - some functional component must be defined and exported. Another unmentioned bit to this is that you can perform any logic in that block which you need, not just checking request params; e.g., you could have the server make a request for a valid session first and evaluate based on that instead.
    – bsplosion
    Jul 6, 2021 at 15:42
6

It's a good idea for SEO to redirect server side if you can (not for login like the questions mention).

But for things like user language etc it's probably a good idea to use server side redirects like this. ----- REMOVED since it was bad code --------

Update, I ended up with this as I did have some problems with headers already sent. Please let me know how this can be fixed as it's not the most ideal (although Google does understand it according to this article https://www.seroundtable.com/google-meta-refresh-redirects-work-25335.html)

export default function HomePage({ language }) {
  return (
    <Head>
      <title>-</title>
      <meta httpEquiv="refresh" content={`0;url=/${language}/discover/0`} />
    </Head>
  );
}

Update Nextjs is adding native support there is an RFC available: https://github.com/vercel/next.js/discussions/17078

-11

With Next.JS, you need to redirect the client on the client side. Try to return a 200 status code if the login is successful and then use the client router on success to navigate to another page. This example should give you an idea on how you can programmatically push a new page to the router history:

import Router from 'next/router'

() => {
  if(code==200){
    Router.push('/')
  }
}
4
  • 4
    In my opinion, this answer is confusing and the provided snippet doesn't clarify much. You can redirect both client and server side. On the client, take a look at router.push or router.replaceAPIs. On the server, you could force a 301, 303 or 308 (all typical redirection HTTP status) by writing an explicit header, via ctx.res.writeHead(303, { Location: target }). Jun 23, 2020 at 1:10
  • I'm not sure if the redirect works if you use fetch on the client side, have you tested this behavior? Anyways, if you are not satisfied with this answer please go ahead and add your own answer to this question, so others do not need to lookup a better answer in a comment of another answer.
    – Jan Peter
    Jun 24, 2020 at 7:58
  • 1
    Not sure how fetch comes into the equation here. Yes, the mentioned approaches work. Take a look at next-redirect for an example implementation. I didn't want to add a new answer, seeing as it's customary on this site to comment on accepted answers first - which is also what people usually look for. Jun 24, 2020 at 11:26
  • Hmm. I like it on the server since the whole point of Next is SEO and I don't think Google will get a client side redirect. Jul 29, 2020 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.