NextJs Package

The Memberstack NextJs package is a wrapper around @memberstack/react while also containing server actions that can be use with the latest app router and still with getServerSideProps.

Getting Started

First, you'll need to install the Memberstack Nextjs package:

npm install @memberstack/nextjs

You have access to client side packages at @memberstack/nextjs/client. Wrap the children routes of your app with MemberstackProvider.

App Router

For the app router, that means in app/layout.tsx

// layout.tsx
import './globals.css'
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import { MemberstackProvider } from '@memberstack/nextjs/client'

const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <MemberstackProvider config={{
          publicKey: process.env.NEXT_PUBLIC_MEMBERSTACK_PUBLIC_KEY as string
        }}>
          <>{children}</>
        </MemberstackProvider>
      </body>
    </html>
  )
}

Pages Directory

Or if you're using the pages router, inside pages/_app.tsx

import type { AppProps } from 'next/app'
import { MemberstackProvider } from '@memberstack/nextjs/client'

export default function App({ Component, pageProps }: AppProps) {
  return <MemberstackProvider config={{
    publicKey: process.env.NEXT_PUBLIC_MEMBERSTACK_PUBLIC_KEY as string
  }}>
    <Component {...pageProps} />
  </MemberstackProvider>
}

You can then access all the same react components on the client

'use client'

import { MemberstackProtected, SignInModal, useAuth } from "@memberstack/nextjs/client"

...

const {userId, signOut, isLoggedIn } = useAuth()

...

<MemberstackProtected
  fallback={<div>Loading.....</div>} 
  onUnauthorized={<SignInModal/>}
>
...
</MemberstackProtected>

Last updated