Next-auth: Correct behavior for redirecting signed-in users to the dashboard

Created on 23 Jun 2020  路  6Comments  路  Source: nextauthjs/next-auth

I have next-auth 2.0 running and it works great. Thank you for the awesome project.

Your question
Where to put the logic (across my app) to see if there's a session, then redirect to dashboard?

Further explanation.

I have a question regarding the behavior for when a user is logged in and they visit the homepage (the landing page). Typically most apps redirect the user to the main page of the dashboard (main screen when signed in) seamlessly and quite fast. An example of that is dropbox. The redirect happens instantly with no loading except for the loading of the dashboard itself.

In a NextJS app, where should I put the logic so that if a user visits any of the public pages, and they are signed in (session exists), I redirect them fast without showing the initial screen that they requested.

How is Provider component helpful?

Also, in the sample repo, what's the point of the <Provider state={session}> if the session is read per page (from pageProps), so every page would have to make the same request getSession(context) then my app would just be SSR for every page and I'm not benefiting from sharing session between pages in memory. Am I missing something?

What are you trying to do
I'm trying to see if there's a session when a user visits any page, if it's a protected page and I have a session, let them through. If I have a session and they visit a public page, redirect them to in-app home page.

  • [x] Found documentation but was incomplete
question

All 6 comments

I don't know if this is the best way to do this, but what I normally do is, in my pages/index.js I check for the client session object, and if its not there (not logged in) I render a login form, if the object is there (logged in) then I render the main logged in page. This requires no redirect and logged in users land right at the primary dashboard page.

For example:

import NextAuth from 'next-auth/client'

const Index = ({ session }) => {
  if (typeof window !== 'undefined' && !session) {
    Router.push('/api/auth/signin')
  }

  if (session) {
    return (
      <Layout>
        <Panel header='Maintenance'>
          <div className='grid-container'>
            <div className='unread'>
              <UnreadBadge count={mailCount} />
            </div>
            <div className='heatmap'>
              <Heatmap />
            </div>
            <div className='recents'>
              <ActiveMaintenances />
            </div>
            <div className='chart1'>
              <AreaChart />
            </div>
            <div className='chart2'>
              <BarChart />
            </div>
          </div>
        </MaintPanel>
      </Layout>
    )
  } else {
    return <RequireLogin />
  }
}

export async function getServerSideProps({ req, res }) {
  const session = await NextAuth.session({ req })
  if (!session) {
    if (req) {
      res.writeHead(302, { Location: '/api/auth/signin' })
      res.end()
    } else {
      Router.push('/api/auth/signin')
    }
  }
  return {
    props: {
      session,
    },
  }
}

@ndom91 Thanks for your answer and code example.

That mean if I visit /about page in your app, I won't get redirected, correct?

Also, does that mean your home page / will be SSR, so it won't, not a benefiting from NextJS static optimization?

Is there a way to have both worlds? :D

Yes, this would be SSR haha unfortunately thats how all my experience has been with this library so far so I can't help you further with that, but logically I dont think its possible. It can't know if the user is logged in or not at build time.

If you want the about page to be open to everyone, then simply don't do the if (session) ... check before rendering it.

Yeah, I get you. Thanks again.

Just to second that, yeah basically exactly as @ndom91 said is really the way to do it :-)

If you use getInitialProps() instead of getServerSideProps() with exactly the same code (as above) then you don't need to have logic in the render, which is what I think he meant to do (req is there during server side rendering, but not client side).

How is Provider component helpful?

The provider component allows you to share the session object between pages (and from server side render to client side render), reducing the number of network calls (as per the documentation for the <Provider>).

This is explained in the documentation for the provider.

Screenshot 2020-06-24 at 01 06 38

In the example, _app.js is only run server side when accessing a page when not navigating inside a single page app. It won't make all page renders server side only.

The documentation also links out to the Next.js page for _app.js and React Context for further reading, so I'm pretty happy it's complete in that regard.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

benoror picture benoror  路  3Comments

simonbbyrne picture simonbbyrne  路  3Comments

alephart picture alephart  路  3Comments

ryanditjia picture ryanditjia  路  3Comments

ghoshnirmalya picture ghoshnirmalya  路  3Comments