Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting from server side in NextJS

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('/')
    }
}) 
like image 316
Pavindu Avatar asked Feb 09 '19 08:02

Pavindu


2 Answers

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(req.body.username == "user" && req.body.password == "123"){
    return {
      redirect: {
        permanent: false,
        destination: "/"
      }
    }
  }
}
like image 110
bsplosion Avatar answered Oct 05 '22 07:10

bsplosion


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.

export const getServerSideProps = async ({ req, res }) => {
if (res) {
    res.writeHead(302, { // or 301
      Location: "localized/url/product/categories",
    });
    res.end();
  }
}

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

like image 23
Richard Lindhout Avatar answered Oct 05 '22 07:10

Richard Lindhout