Unverified Commit 41efb824 authored by Rishabh Poddar's avatar Rishabh Poddar Committed by GitHub

Docs update: Adds supertokens to 'Bring Your Own Database' section as well +…

Docs update: Adds supertokens to 'Bring Your Own Database' section as well + improvements to code structure in example (#23779)

- Since SuperTokens is a self hosted solution, it can be added to 'Bring Your Own Database' as well (in https://nextjs.org/docs/authentication#supertokens)
- Improvements to code structure in the with-supertokens example
parent dbb63850
...@@ -196,7 +196,7 @@ You can either use [FirebaseUI](https://github.com/firebase/firebaseui-web-react ...@@ -196,7 +196,7 @@ You can either use [FirebaseUI](https://github.com/firebase/firebaseui-web-react
</details> </details>
[SuperTokens](https://supertokens.io) is a highly customizable, open-source solution split into modules (so you only use what you need). [SuperTokens](https://supertokens.io) is a highly customizable, open-source solution split into modules (so you only use what you need).
SuperTokens currently supports credentials login, email verification, password reset flows, and third-party logins. SuperTokens currently supports credentials login, email verification, password reset flows, third-party logins, and cookie based sessions with rotating refresh tokens.
## Related ## Related
......
...@@ -2,10 +2,6 @@ ...@@ -2,10 +2,6 @@
This is a simple set up for applications protected by SuperTokens. This is a simple set up for applications protected by SuperTokens.
The SuperTokens back end configurations are in `supertokens.js`.
The SuperTokens front end configurations are in `pages/_app.js`.
## Deploy your own ## Deploy your own
Deploy the example using [Vercel](https://vercel.com): Deploy the example using [Vercel](https://vercel.com):
...@@ -24,11 +20,13 @@ yarn create next-app --example with-supertokens with-supertokens-app ...@@ -24,11 +20,13 @@ yarn create next-app --example with-supertokens with-supertokens-app
## Configuration ## Configuration
Create a `.env.local` file and copy the content of `.env.local.example` into it: - Create a `.env.local` file and copy the content of `.env.local.example` into it:
```bash ```bash
cp .env.local.example .env.local cp .env.local.example .env.local
``` ```
- Fill in the values for your social login secrets
## Deploy on Vercel ## Deploy on Vercel
...@@ -42,6 +40,4 @@ To deploy your local project to Vercel, push it to GitHub/GitLab/Bitbucket and [ ...@@ -42,6 +40,4 @@ To deploy your local project to Vercel, push it to GitHub/GitLab/Bitbucket and [
## Notes ## Notes
Take a look at [SuperTokens documentation](https://supertokens.io/docs/emailpassword/introduction) to configure SuperTokens for your project. Take a look at [SuperTokens documentation](https://supertokens.io/docs/community/introduction).
Especially, you will want to replace the use of the demo SuperTokens core with your own SuperTokens core instance. See https://supertokens.io/docs/emailpassword/quick-setup/supertokens-core/overview.
import ThirdPartyEmailPasswordNode from 'supertokens-node/recipe/thirdpartyemailpassword'
import SessionNode from 'supertokens-node/recipe/session'
import ThirdPartyEmailPasswordReact from 'supertokens-auth-react/recipe/thirdpartyemailpassword'
import SessionReact from 'supertokens-auth-react/recipe/session'
const port = process.env.APP_PORT || 3000
const websiteDomain =
process.env.APP_URL ||
process.env.NEXT_PUBLIC_APP_URL ||
`http://localhost:${port}`
const apiBasePath = '/api/auth/'
let appInfo = {
appName: 'SuperTokens Demo App',
websiteDomain,
apiDomain: websiteDomain,
apiBasePath,
}
export let backendConfig = () => {
return {
supertokens: {
connectionURI: 'https://try.supertokens.io',
},
appInfo,
recipeList: [
ThirdPartyEmailPasswordNode.init({
providers: [
ThirdPartyEmailPasswordNode.Google({
clientSecret: process.env.GOOGLE_CLIENT_SECRET || 'PLACEHOLDER',
clientId: process.env.GOOGLE_CLIENT_ID || 'PLACEHOLDER',
}),
ThirdPartyEmailPasswordNode.Github({
clientSecret: process.env.GITHUB_CLIENT_SECRET || 'PLACEHOLDER',
clientId: process.env.GITHUB_CLIENT_ID || 'PLACEHOLDER',
}),
ThirdPartyEmailPasswordNode.Facebook({
clientSecret: process.env.FACEBOOK_CLIENT_SECRET || 'PLACEHOLDER',
clientId: process.env.FACEBOOK_CLIENT_ID || 'PLACEHOLDER',
}),
],
}),
SessionNode.init(),
],
isInServerlessEnv: true,
}
}
export let frontendConfig = () => {
return {
useReactRouterDom: false,
appInfo,
recipeList: [
ThirdPartyEmailPasswordReact.init({
emailVerificationFeature: {
mode: 'REQUIRED',
},
signInAndUpFeature: {
providers: [
ThirdPartyEmailPasswordReact.Google.init(),
ThirdPartyEmailPasswordReact.Github.init(),
ThirdPartyEmailPasswordReact.Facebook.init(),
],
},
}),
SessionReact.init(),
],
}
}
...@@ -11,8 +11,8 @@ ...@@ -11,8 +11,8 @@
"next": "latest", "next": "latest",
"react": "17.0.1", "react": "17.0.1",
"react-dom": "17.0.1", "react-dom": "17.0.1",
"supertokens-auth-react": "^0.8", "supertokens-auth-react": "^0.9.0",
"supertokens-node": "^4.2.0" "supertokens-node": "^4.3.0"
}, },
"license": "MIT" "license": "MIT"
} }
import '../styles/globals.css' import '../styles/globals.css'
import React from 'react' import React from 'react'
import { useEffect } from 'react'
import SuperTokensReact from 'supertokens-auth-react' import SuperTokensReact from 'supertokens-auth-react'
import ThirdPartyEmailPasswordReact from 'supertokens-auth-react/recipe/thirdpartyemailpassword' import * as SuperTokensConfig from '../config/supertokensConfig'
import SessionReact from 'supertokens-auth-react/recipe/session' import Session from 'supertokens-auth-react/recipe/session'
import SuperTokensNode from 'supertokens-node' import SuperTokensNode from 'supertokens-node'
import SessionNode from 'supertokens-node/recipe/session' import { redirectToAuth } from 'supertokens-auth-react/recipe/thirdpartyemailpassword'
import ThirdPartyEmailPasswordNode from 'supertokens-node/recipe/thirdpartyemailpassword'
const port = process.env.APP_PORT || 3000
const websiteDomain =
process.env.APP_URL ||
process.env.NEXT_PUBLIC_APP_URL ||
`http://localhost:${port}`
const apiBasePath = '/api/auth/'
// Client Side configs.
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
SuperTokensReact.init({ SuperTokensReact.init(SuperTokensConfig.frontendConfig())
useReactRouterDom: false,
appInfo: {
appName: 'SuperTokens Demo App',
websiteDomain,
apiDomain: websiteDomain,
apiBasePath,
},
recipeList: [
ThirdPartyEmailPasswordReact.init({
emailVerificationFeature: {
mode: 'REQUIRED',
},
signInAndUpFeature: {
providers: [
ThirdPartyEmailPasswordReact.Google.init(),
ThirdPartyEmailPasswordReact.Github.init(),
ThirdPartyEmailPasswordReact.Facebook.init(),
],
},
}),
SessionReact.init(),
],
})
} else { } else {
// Server Side configs. SuperTokensNode.init(SuperTokensConfig.backendConfig())
SuperTokensNode.init({
supertokens: {
connectionURI: 'https://try.supertokens.io', // Replace with your SuperTokens core instance. See https://supertokens.io/docs/emailpassword/quick-setup/supertokens-core/overview
},
appInfo: {
appName: 'SuperTokens Demo App',
websiteDomain,
apiDomain: websiteDomain,
apiBasePath,
},
recipeList: [
ThirdPartyEmailPasswordNode.init({
providers: [
ThirdPartyEmailPasswordNode.Google({
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
clientId: process.env.GOOGLE_CLIENT_ID,
}),
ThirdPartyEmailPasswordNode.Github({
clientSecret: process.env.GITHUB_CLIENT_SECRET,
clientId: process.env.GITHUB_CLIENT_ID,
}),
ThirdPartyEmailPasswordNode.Facebook({
clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
clientId: process.env.FACEBOOK_CLIENT_ID,
}),
],
}),
SessionNode.init(),
],
isInServerlessEnv: true,
})
} }
function MyApp({ Component, pageProps }) { function MyApp({ Component, pageProps }) {
useEffect(() => {
async function doRefresh() {
if (pageProps.fromSupertokens === 'needs-refresh') {
if (await Session.attemptRefreshingSession()) {
location.reload()
} else {
// user has been logged out
redirectToAuth()
}
}
}
doRefresh()
}, [pageProps.fromSupertokens])
if (pageProps.fromSupertokens === 'needs-refresh') {
return null
}
return <Component {...pageProps} /> return <Component {...pageProps} />
} }
......
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { superTokensNextWrapper } from 'supertokens-node/nextjs' import { superTokensNextWrapper } from 'supertokens-node/nextjs'
import { middleware } from 'supertokens-node' import supertokens from 'supertokens-node'
import * as SuperTokensConfig from '../../../config/supertokensConfig'
supertokens.init(SuperTokensConfig.backendConfig())
export default async function superTokens(req, res) { export default async function superTokens(req, res) {
return await superTokensNextWrapper( await superTokensNextWrapper(
async (next) => { async (next) => {
await middleware()(req, res, next) await supertokens.middleware()(req, res, next)
}, },
req, req,
res res
) )
if (!res.writableEnded) {
res.status(404).send('Not found')
}
} }
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { superTokensNextWrapper } from 'supertokens-node/nextjs' import { superTokensNextWrapper } from 'supertokens-node/nextjs'
import { verifySession } from 'supertokens-node/recipe/session' import { verifySession } from 'supertokens-node/recipe/session'
import supertokens from 'supertokens-node'
import * as SuperTokensConfig from '../../config/supertokensConfig'
export default async function user(req, res) { supertokens.init(SuperTokensConfig.backendConfig())
if (req.method !== 'GET') {
return res.end()
}
export default async function user(req, res) {
await superTokensNextWrapper( await superTokensNextWrapper(
async (next) => { async (next) => {
return await verifySession()(req, res, next) return await verifySession()(req, res, next)
...@@ -18,8 +17,8 @@ export default async function user(req, res) { ...@@ -18,8 +17,8 @@ export default async function user(req, res) {
return res.json({ return res.json({
note: note:
'Fetch any data from your application for authenticated user after using verifySession middleware', 'Fetch any data from your application for authenticated user after using verifySession middleware',
userId: req.session.userId, userId: req.session.getUserId(),
sessionHandle: req.session.sessionHandle, sessionHandle: req.session.getHandle(),
userDataInJWT: req.session.userDataInJWT, userDataInJWT: req.session.getJWTPayload(),
}) })
} }
...@@ -3,21 +3,17 @@ import React, { useEffect } from 'react' ...@@ -3,21 +3,17 @@ import React, { useEffect } from 'react'
import styles from '../../styles/Home.module.css' import styles from '../../styles/Home.module.css'
import dynamic from 'next/dynamic' import dynamic from 'next/dynamic'
import SuperTokens from 'supertokens-auth-react' import SuperTokens from 'supertokens-auth-react'
import { redirectToAuth } from 'supertokens-auth-react/recipe/thirdpartyemailpassword'
const SuperTokensComponentNoSSR = dynamic( const SuperTokensComponentNoSSR = dynamic(
() => new Promise((res) => res(SuperTokens.getRoutingComponent)),
Promise.resolve().then(() => { { ssr: false }
return () => SuperTokens.getRoutingComponent() || null
}),
{
ssr: false,
}
) )
export default function Auth() { export default function Auth() {
useEffect(() => { useEffect(() => {
if (SuperTokens.canHandleRoute() === false) { if (SuperTokens.canHandleRoute() === false) {
window.location.href = '/' redirectToAuth()
} }
}, []) }, [])
......
...@@ -3,18 +3,43 @@ import Head from 'next/head' ...@@ -3,18 +3,43 @@ import Head from 'next/head'
import styles from '../styles/Home.module.css' import styles from '../styles/Home.module.css'
import ThirdPartyEmailPassword from 'supertokens-auth-react/recipe/thirdpartyemailpassword' import ThirdPartyEmailPassword from 'supertokens-auth-react/recipe/thirdpartyemailpassword'
import dynamic from 'next/dynamic' import dynamic from 'next/dynamic'
import Session from 'supertokens-node/recipe/session'
const ThirdPartyEmailPasswordAuthNoSSR = dynamic( const ThirdPartyEmailPasswordAuthNoSSR = dynamic(
() => new Promise((res) =>
Promise.resolve().then( res(ThirdPartyEmailPassword.ThirdPartyEmailPasswordAuth)
() => ThirdPartyEmailPassword.ThirdPartyEmailPasswordAuth ),
), { ssr: false }
{
ssr: false,
}
) )
export default function Home() { export async function getServerSideProps(context) {
let session
try {
session = await Session.getSession(context.req, context.res)
} catch (err) {
if (err.type === Session.Error.TRY_REFRESH_TOKEN) {
return { props: { fromSupertokens: 'needs-refresh' } }
} else if (err.type === Session.Error.UNAUTHORISED) {
return { props: {} }
} else {
throw err
}
}
return {
props: { userId: session.getUserId() },
}
}
export default function Home(props) {
return (
<ThirdPartyEmailPasswordAuthNoSSR>
<ProtectedPage userId={props.userId} />
</ThirdPartyEmailPasswordAuthNoSSR>
)
}
function ProtectedPage({ userId }) {
async function logoutClicked() { async function logoutClicked() {
await ThirdPartyEmailPassword.signOut() await ThirdPartyEmailPassword.signOut()
window.location.href = '/auth' window.location.href = '/auth'
...@@ -37,68 +62,66 @@ export default function Home() { ...@@ -37,68 +62,66 @@ export default function Home() {
<h1 className={styles.title}> <h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js!</a> Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1> </h1>
<ThirdPartyEmailPasswordAuthNoSSR> <p className={styles.description}>
<p className={styles.description}> You are authenticated with SuperTokens! (UserID: {userId})
You are authenticated with SuperTokens! </p>
</p>
<div
style={{
display: 'flex',
height: '70px',
alignItems: 'center',
justifyContent: 'flex-end',
paddingLeft: '75px',
paddingRight: '75px',
}}
>
<div <div
onClick={logoutClicked}
style={{ style={{
display: 'flex', display: 'flex',
height: '70px', width: '116px',
height: '42px',
backgroundColor: '#000000',
borderRadius: '10px',
cursor: 'pointer',
alignItems: 'center', alignItems: 'center',
justifyContent: 'flex-end', justifyContent: 'center',
paddingLeft: '75px', color: '#ffffff',
paddingRight: '75px', fontWeight: 'bold',
}} }}
> >
<div SIGN OUT
onClick={logoutClicked}
style={{
display: 'flex',
width: '116px',
height: '42px',
backgroundColor: '#000000',
borderRadius: '10px',
cursor: 'pointer',
alignItems: 'center',
justifyContent: 'center',
color: '#ffffff',
fontWeight: 'bold',
}}
>
SIGN OUT
</div>
</div> </div>
</div>
<div
style={{
display: 'flex',
height: '70px',
alignItems: 'center',
justifyContent: 'flex-end',
paddingLeft: '75px',
paddingRight: '75px',
}}
>
<div <div
onClick={fetchUserData}
style={{ style={{
display: 'flex', display: 'flex',
height: '70px', width: '150px',
height: '42px',
backgroundColor: 'rgb(247 54 54)',
borderRadius: '10px',
cursor: 'pointer',
alignItems: 'center', alignItems: 'center',
justifyContent: 'flex-end', justifyContent: 'center',
paddingLeft: '75px', color: '#ffffff',
paddingRight: '75px', fontWeight: 'bold',
}} }}
> >
<div FETCH USER API
onClick={fetchUserData}
style={{
display: 'flex',
width: '150px',
height: '42px',
backgroundColor: 'rgb(247 54 54)',
borderRadius: '10px',
cursor: 'pointer',
alignItems: 'center',
justifyContent: 'center',
color: '#ffffff',
fontWeight: 'bold',
}}
>
FETCH USER API
</div>
</div> </div>
</ThirdPartyEmailPasswordAuthNoSSR> </div>
<div className={styles.grid}> <div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}> <a href="https://nextjs.org/docs" className={styles.card}>
...@@ -130,7 +153,6 @@ export default function Home() { ...@@ -130,7 +153,6 @@ export default function Home() {
</a> </a>
</div> </div>
</main> </main>
<footer className={styles.footer}> <footer className={styles.footer}>
<a <a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app" href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment