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
</details>
[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
......
......@@ -2,10 +2,6 @@
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 the example using [Vercel](https://vercel.com):
......@@ -24,11 +20,13 @@ yarn create next-app --example with-supertokens with-supertokens-app
## 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
cp .env.local.example .env.local
```
```bash
cp .env.local.example .env.local
```
- Fill in the values for your social login secrets
## Deploy on Vercel
......@@ -42,6 +40,4 @@ To deploy your local project to Vercel, push it to GitHub/GitLab/Bitbucket and [
## Notes
Take a look at [SuperTokens documentation](https://supertokens.io/docs/emailpassword/introduction) to configure SuperTokens for your project.
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.
Take a look at [SuperTokens documentation](https://supertokens.io/docs/community/introduction).
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 @@
"next": "latest",
"react": "17.0.1",
"react-dom": "17.0.1",
"supertokens-auth-react": "^0.8",
"supertokens-node": "^4.2.0"
"supertokens-auth-react": "^0.9.0",
"supertokens-node": "^4.3.0"
},
"license": "MIT"
}
import '../styles/globals.css'
import React from 'react'
import { useEffect } from 'react'
import SuperTokensReact from 'supertokens-auth-react'
import ThirdPartyEmailPasswordReact from 'supertokens-auth-react/recipe/thirdpartyemailpassword'
import SessionReact from 'supertokens-auth-react/recipe/session'
import * as SuperTokensConfig from '../config/supertokensConfig'
import Session from 'supertokens-auth-react/recipe/session'
import SuperTokensNode from 'supertokens-node'
import SessionNode from 'supertokens-node/recipe/session'
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/'
import { redirectToAuth } from 'supertokens-auth-react/recipe/thirdpartyemailpassword'
// Client Side configs.
if (typeof window !== 'undefined') {
SuperTokensReact.init({
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(),
],
})
SuperTokensReact.init(SuperTokensConfig.frontendConfig())
} else {
// Server Side configs.
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,
})
SuperTokensNode.init(SuperTokensConfig.backendConfig())
}
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} />
}
......
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
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) {
return await superTokensNextWrapper(
await superTokensNextWrapper(
async (next) => {
await middleware()(req, res, next)
await supertokens.middleware()(req, res, next)
},
req,
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 { verifySession } from 'supertokens-node/recipe/session'
import supertokens from 'supertokens-node'
import * as SuperTokensConfig from '../../config/supertokensConfig'
export default async function user(req, res) {
if (req.method !== 'GET') {
return res.end()
}
supertokens.init(SuperTokensConfig.backendConfig())
export default async function user(req, res) {
await superTokensNextWrapper(
async (next) => {
return await verifySession()(req, res, next)
......@@ -18,8 +17,8 @@ export default async function user(req, res) {
return res.json({
note:
'Fetch any data from your application for authenticated user after using verifySession middleware',
userId: req.session.userId,
sessionHandle: req.session.sessionHandle,
userDataInJWT: req.session.userDataInJWT,
userId: req.session.getUserId(),
sessionHandle: req.session.getHandle(),
userDataInJWT: req.session.getJWTPayload(),
})
}
......@@ -3,21 +3,17 @@ import React, { useEffect } from 'react'
import styles from '../../styles/Home.module.css'
import dynamic from 'next/dynamic'
import SuperTokens from 'supertokens-auth-react'
import { redirectToAuth } from 'supertokens-auth-react/recipe/thirdpartyemailpassword'
const SuperTokensComponentNoSSR = dynamic(
() =>
Promise.resolve().then(() => {
return () => SuperTokens.getRoutingComponent() || null
}),
{
ssr: false,
}
new Promise((res) => res(SuperTokens.getRoutingComponent)),
{ ssr: false }
)
export default function Auth() {
useEffect(() => {
if (SuperTokens.canHandleRoute() === false) {
window.location.href = '/'
redirectToAuth()
}
}, [])
......
......@@ -3,18 +3,43 @@ import Head from 'next/head'
import styles from '../styles/Home.module.css'
import ThirdPartyEmailPassword from 'supertokens-auth-react/recipe/thirdpartyemailpassword'
import dynamic from 'next/dynamic'
import Session from 'supertokens-node/recipe/session'
const ThirdPartyEmailPasswordAuthNoSSR = dynamic(
() =>
Promise.resolve().then(
() => ThirdPartyEmailPassword.ThirdPartyEmailPasswordAuth
),
{
ssr: false,
}
new Promise((res) =>
res(ThirdPartyEmailPassword.ThirdPartyEmailPasswordAuth)
),
{ 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() {
await ThirdPartyEmailPassword.signOut()
window.location.href = '/auth'
......@@ -37,68 +62,66 @@ export default function Home() {
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1>
<ThirdPartyEmailPasswordAuthNoSSR>
<p className={styles.description}>
You are authenticated with SuperTokens!
</p>
<p className={styles.description}>
You are authenticated with SuperTokens! (UserID: {userId})
</p>
<div
style={{
display: 'flex',
height: '70px',
alignItems: 'center',
justifyContent: 'flex-end',
paddingLeft: '75px',
paddingRight: '75px',
}}
>
<div
onClick={logoutClicked}
style={{
display: 'flex',
height: '70px',
width: '116px',
height: '42px',
backgroundColor: '#000000',
borderRadius: '10px',
cursor: 'pointer',
alignItems: 'center',
justifyContent: 'flex-end',
paddingLeft: '75px',
paddingRight: '75px',
justifyContent: 'center',
color: '#ffffff',
fontWeight: 'bold',
}}
>
<div
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>
SIGN OUT
</div>
</div>
<div
style={{
display: 'flex',
height: '70px',
alignItems: 'center',
justifyContent: 'flex-end',
paddingLeft: '75px',
paddingRight: '75px',
}}
>
<div
onClick={fetchUserData}
style={{
display: 'flex',
height: '70px',
width: '150px',
height: '42px',
backgroundColor: 'rgb(247 54 54)',
borderRadius: '10px',
cursor: 'pointer',
alignItems: 'center',
justifyContent: 'flex-end',
paddingLeft: '75px',
paddingRight: '75px',
justifyContent: 'center',
color: '#ffffff',
fontWeight: 'bold',
}}
>
<div
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>
FETCH USER API
</div>
</ThirdPartyEmailPasswordAuthNoSSR>
</div>
<div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
......@@ -130,7 +153,6 @@ export default function Home() {
</a>
</div>
</main>
<footer className={styles.footer}>
<a
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