Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authentication and protecting routes with NextJS #2

Open
StefanEissler opened this issue Sep 22, 2023 · 1 comment
Open

Authentication and protecting routes with NextJS #2

StefanEissler opened this issue Sep 22, 2023 · 1 comment

Comments

@StefanEissler
Copy link

Hello,
very nicley done project!
I am currently working on a similar one.
But I can´t figure out the authentication fully.
I can login and logout users. But I can´t figure out how to protect routes and redirect Users to the login page if they are not logged in.
Also I have problems to get the data of the user that is currently logged in.
Can you help me with that?
Kind regards,
Stefan

@StefanEissler
Copy link
Author

import '@tamagui/core/reset.css'
import '@tamagui/font-inter/css/400.css'
import '@tamagui/font-inter/css/700.css'
import 'raf/polyfill'

import { NextThemeProvider, useRootTheme } from '@tamagui/next-theme'
import { Provider } from 'app/provider'
import Head from 'next/head'
import React, { useEffect, useMemo } from 'react'
import type { SolitoAppProps } from 'solito'
import Layout from 'components/layout'
import { UserProvider } from '../../../packages/supabase/src/contexts/user'
import { supabaseClient } from '../../../packages/supabase/src/clients/supabase'
import App from 'next/app'
import type { User } from '@supabase/supabase-js'
import { useRouter } from 'next/router'


if (process.env.NODE_ENV === 'production') {
  require('../public/tamagui.css')
}

interface MyAppProps extends SolitoAppProps {
  ssrUserData?: User | null
}

function MyApp({ Component, pageProps, ssrUserData }: MyAppProps) {

  const router = useRouter();

  const isUserLoggedIn = ssrUserData !== null;

  useEffect(() => {
    if (!isUserLoggedIn) {
      router.push('/login'); // Hier musst du den richtigen Pfad zur Login-Seite angeben
    }
  }, [isUserLoggedIn]);

  const contents = useMemo(() => {
    return (
      // @ts-ignore
      <Component {...pageProps} />
    )
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageProps])
  
  return (
    <>
      <Head>
        <title>Ensemble</title>
        <meta name="description" content="Tamagui, Solito, Expo & Next.js" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <ThemeProvider>
          {contents}
      </ThemeProvider>
    </>
  )
}

function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [theme, setTheme] = useRootTheme()

  return (
    <NextThemeProvider
      onChangeTheme={(next) => {
        setTheme(next as any)
      }}
    >
      <Provider disableRootThemeClass defaultTheme={theme}>
        <Layout>
          {children}
        </Layout>
      </Provider>
    </NextThemeProvider>
  )
}

MyApp.getInitialProps = async (appContext: any) => {
  const appProps = await App.getInitialProps(appContext);

  const { data: userData, token  } = await supabaseClient
    .auth
    .api
    .getUserByCookie(appContext.ctx.req)

  return { 
    ...appProps, 
    ssrUserData: userData ?? null,
  }
}

export default MyApp

`

I tried it like this in my __app.tsx. But now the page is loading and then the user gets redirected to the login page...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant