Create a Dashboard

Redirect when there is no user

If someone visits our edit blog post page without a login, we need to redirect that user to the blog homepage. Let's do that.

Open the pages/dashboard/post/[slug].js and replace the getServerSideProps with the following codebase:

export async function getServerSideProps({ req, res, params }) {
  const session = await getSession({ req })
  if (!session) {
    res.writeHead(302, {
      'Location': '/'
    return { props: {} }

  const post = await getPost(params.slug, { ownerId: })

  return {
    props: {

As you can see, we are trying to redirect the user with res.writeHead to the path / if there's no session.

šŸ’” Next.js adds the original HTTP response object to getServerSideProps as res. That allows us to do things like this.

Now, try to implement this functionality. Then answer the following question.

We have two other pages that need an authenticated user. They are:

  • /dashboard
  • /dashboard/post/create
Q: Can we implement a simple auth redirect in those pages?

šŸ™ We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: