Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

remove or warn about getSession calls in docs (#20308)

Charis94a07fe7245b
diff --git a/apps/docs/components/MDX/get_session_warning.mdx b/apps/docs/components/MDX/get_session_warning.mdx
new file mode 100644
index 00000000000..937b7792730
--- /dev/null
+++ b/apps/docs/components/MDX/get_session_warning.mdx
@@ -0,0 +1,7 @@
+<Admonition type="danger">
+
+Note that `auth.getSession` reads the auth token and the unencoded session data from the local storage medium. It _doesn't_ send a request back to the Supabase Auth server unless the local session is expired.
+
+You should **never** trust the unencoded session data if you're writing server code, since it could be tampered with by the sender. If you need verified, trustworthy user data, call `auth.getUser` instead, which always makes a request to the Auth server to fetch trusted data.
+
+</Admonition>
diff --git a/apps/docs/components/index.tsx b/apps/docs/components/index.tsx
index 05dbf458a23..d8f550820a0 100644
--- a/apps/docs/components/index.tsx
+++ b/apps/docs/components/index.tsx
@@ -14,6 +14,7 @@ import SocialProviderSettingsSupabase from './MDX/social_provider_settings_supab
import SocialProviderSetup from './MDX/social_provider_setup.mdx'
import StorageManagement from './MDX/storage_management.mdx'
import MigrationWarnings from './MDX/migration_warnings.mdx'
+import GetSessionWarning from './MDX/get_session_warning.mdx'
import { CH } from '@code-hike/mdx/components'
import RefHeaderSection from './reference/RefHeaderSection'
@@ -60,6 +61,7 @@ const components = {
DatabaseSetup,
ProjectSetup,
MigrationWarnings,
+ GetSessionWarning,
SocialProviderSetup,
SocialProviderSettingsSupabase,
StepHikeCompact,
diff --git a/apps/docs/docs/ref/javascript/v1/upgrade-guide.mdx b/apps/docs/docs/ref/javascript/v1/upgrade-guide.mdx
index 36b040b0aa9..f42d77c827a 100644
--- a/apps/docs/docs/ref/javascript/v1/upgrade-guide.mdx
+++ b/apps/docs/docs/ref/javascript/v1/upgrade-guide.mdx
@@ -304,6 +304,8 @@ const { data, error } = await supabase
#### Get the user's current session
+<GetSessionWarning />
+
</RefSubLayout.Details>
<RefSubLayout.Examples>
@@ -361,9 +363,8 @@ const user = supabase.auth.user()
```ts
const {
- data: { session },
-} = await supabase.auth.getSession()
-const { user } = session
+ data: { user },
+} = await supabase.auth.getUser()
```
</TabPanel>
diff --git a/apps/docs/pages/guides/auth/auth-helpers/nextjs-pages.mdx b/apps/docs/pages/guides/auth/auth-helpers/nextjs-pages.mdx
index 51966eaa264..87e06bf3010 100644
--- a/apps/docs/pages/guides/auth/auth-helpers/nextjs-pages.mdx
+++ b/apps/docs/pages/guides/auth/auth-helpers/nextjs-pages.mdx
@@ -282,12 +282,12 @@ export default function Profile({ user }) {
export const getServerSideProps = async (ctx) => {
// Create authenticated Supabase Client
const supabase = createPagesServerClient(ctx)
- // Check if we have a session
+ // Check if we have a user
const {
- data: { session },
- } = await supabase.auth.getSession()
+ data: { user },
+ } = await supabase.auth.getUser()
- if (!session)
+ if (!user)
return {
redirect: {
destination: '/',
@@ -297,8 +297,7 @@ export const getServerSideProps = async (ctx) => {
return {
props: {
- initialSession: session,
- user: session.user,
+ user,
},
}
}
@@ -335,8 +334,8 @@ export const getServerSideProps = async (ctx) => {
const supabase = createPagesServerClient(ctx)
// Check if we have a session
const {
- data: { session },
- } = await supabase.auth.getSession()
+ data: { user },
+ } = await supabase.auth.getUser()
if (!session)
return {
@@ -351,8 +350,7 @@ export const getServerSideProps = async (ctx) => {
return {
props: {
- initialSession: session,
- user: session.user,
+ user,
data: data ?? [],
},
}
@@ -381,10 +379,10 @@ export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
const supabase = createPagesServerClient(ctx)
// Check if we have a session
const {
- data: { session },
- } = await supabase.auth.getSession()
+ data: { user },
+ } = await supabase.auth.getUser()
- if (!session)
+ if (!user)
return {
redirect: {
destination: '/',
@@ -397,8 +395,7 @@ export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
return {
props: {
- initialSession: session,
- user: session.user,
+ user,
data: data ?? [],
},
}
@@ -412,6 +409,10 @@ export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
When using third-party auth providers, sessions are initiated with an additional `provider_token` field which is persisted in the auth cookie and can be accessed within the session object. The `provider_token` can be used to make API requests to the OAuth provider's API endpoints on behalf of the logged-in user.
+Note that the server accesses data on the session object returned by `auth.getSession`. This data should normally not be trusted, because it is read from the local storage medium. It is not revalidated against the Auth server unless the session is expired, which means the sender can tamper with it.
+
+In this case, the third-party API will validate the `provider_token`, and a malicious actor is unable to forge one.
+
<Tabs
scrollable
size="small"
@@ -543,12 +544,12 @@ import { createPagesServerClient } from '@supabase/auth-helpers-nextjs'
const ProtectedRoute = async (req, res) => {
// Create authenticated Supabase Client
const supabase = createPagesServerClient({ req, res })
- // Check if we have a session
+ // Check if we have a user
const {
- data: { session },
- } = await supabase.auth.getSession()
+ data: { user },
+ } = await supabase.auth.getUser()
- if (!session)
+ if (!user)
return res.status(401).json({
error: 'not_authenticated',
description: 'The user does not have an active session or is not authenticated',
@@ -574,10 +575,10 @@ const ProtectedRoute: NextApiHandler = async (req, res) => {
const supabase = createPagesServerClient({ req, res })
// Check if we have a session
const {
- data: { session },
- } = await supabase.auth.getSession()
+ data: { user },
+ } = await supabase.auth.getUser()
- if (!session)
+ if (!user)
return res.status(401).json({
error: 'not_authenticated',
description: 'The user does not have an active session or is not authenticated',
@@ -610,11 +611,11 @@ export async function middleware(req: NextRequest) {
const supabase = createMiddlewareClient({ req, res })
// Check if we have a session
const {
- data: { session },
- } = await supabase.auth.getSession()
+ data: { user },
+ } = await supabase.auth.getUser()
// Check auth condition
- if (session?.user.email?.endsWith('@gmail.com')) {
+ if (user?.email?.endsWith('@gmail.com')) {
// Authentication successful, forward request to protected route.
return res
}
@@ -705,10 +706,10 @@ const ProtectedRoute: NextApiHandler = async (req, res) => {
const supabase = createPagesServerClient({ req, res })
// Check if we have a session
const {
- data: { session },
- } = await supabase.auth.getSession()
+ data: { user },
+ } = await supabase.auth.getUser()
- if (!session)
+ if (!user)
return res.status(401).json({
error: 'not_authenticated',
description: 'The user does not have an active session or is not authenticated',
@@ -764,10 +765,10 @@ export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
const supabase = createPagesServerClient(ctx)
// Check if we have a session
const {
- data: { session },
- } = await supabase.auth.getSession()
+ data: { user },
+ } = await supabase.auth.getUser()
- if (!session)
+ if (!user)
return {
redirect: {
destination: '/',
@@ -831,11 +832,11 @@ export async function middleware(req: NextRequest) {
const supabase = createMiddlewareClient({ req, res })
// Check if we have a session
const {
- data: { session },
- } = await supabase.auth.getSession()
+ data: { user },
+ } = await supabase.auth.getUser()
// Check auth condition
- if (session?.user.email?.endsWith('@gmail.com')) {
+ if (user?.email?.endsWith('@gmail.com')) {
// Authentication successful, forward request to protected route.
return res
}
diff --git a/apps/docs/pages/guides/auth/auth-helpers/remix.mdx b/apps/docs/pages/guides/auth/auth-helpers/remix.mdx
index d8fd0a47fdc..86a3f5d7111 100644
--- a/apps/docs/pages/guides/auth/auth-helpers/remix.mdx
+++ b/apps/docs/pages/guides/auth/auth-helpers/remix.mdx
@@ -285,13 +285,15 @@ const {
} = await supabaseClient.auth.getSession()
```
-The session contains a user property.
+The session contains a user property. This is the user metadata saved, unencoded, to the local storage medium. It's unverified and can be tampered by the user, so don't use it for authorization or sensitive purposes.
+
+<GetSessionWarning />
```jsx
const user = session?.user
```
-Or, if you don't need the session, you can call the `getUser()` function.
+Or, if you need trusted user data, you can call the `getUser()` function, which retrieves the trusted user data by making a request to the Supabase Auth server.
```jsx
const {
diff --git a/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx b/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx
index cf6c6c0acc4..03cc1c47222 100644
--- a/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx
+++ b/apps/docs/pages/guides/auth/auth-helpers/sveltekit.mdx
@@ -46,7 +46,11 @@ PUBLIC_SUPABASE_ANON_KEY=your-anon-key
>
<TabPanel id="js" label="JavaScript">
-Create a new `hooks.server.js` file in the root of your project and populate with the following:
+Create a new `hooks.server.js` file in the root of your project and populate with the following to retrieve the user session.
+
+The session information from `getSession` is supplied to the Supabase client so it can retrieve the auth token. This is safe, since the auth token signature will be revalidated on the Auth server. But you shouldn't trust the unsigned data that is stored alongside the auth token:
+
+<GetSessionWarning />
```js src/hooks.server.js
// src/hooks.server.js
diff --git a/apps/docs/pages/guides/auth/server-side/creating-a-client.mdx b/apps/docs/pages/guides/auth/server-side/creating-a-client.mdx
index 3c172ef1edd..c08a9722a25 100644
--- a/apps/docs/pages/guides/auth/server-side/creating-a-client.mdx
+++ b/apps/docs/pages/guides/auth/server-side/creating-a-client.mdx
@@ -222,7 +222,7 @@ export async function middleware(request: NextRequest) {
}
)
- await supabase.auth.getSession()
+ await supabase.auth.getUser()
return response
}
@@ -423,7 +423,13 @@ export default function Index () {
</TabPanel>
<TabPanel id="sveltekit" label="SvelteKit">
-Creating a Supabase client with the `ssr` package automatically configures it to use Cookies. This means your user's session is available throughout the entire SvelteKit stack - page, layout, server, hooks. It just works!
+Creating a Supabase client with the `ssr` package automatically configures it to use Cookies. This means your user's session is available throughout the entire SvelteKit stack - page, layout, server, hooks.
+
+<Admonition type="danger">
+
+Beware when accessing the session object on the server, because it is not revalidated on every request from the client. That means the sender can tamper with unencoded data in the session object. If you need to verify the integrity of user data for server logic, call `auth.getUser` instead, which will query the Supabase Auth server for trusted user data.
+
+</Admonition>
<Tabs
scrollable
diff --git a/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx b/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx
index 3aafba7f7e5..f07fe9ebaa4 100644
--- a/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx
+++ b/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx
@@ -364,10 +364,10 @@ export async function POST(req) {
// Check if we have a session
const {
- data: { session },
- } = await supabase.auth.getSession()
+ data: { user },
+ } = await supabase.auth.getUser()
- if (session) {
+ if (user) {
await supabase.auth.signOut()
}
@@ -427,14 +427,13 @@ Let's create a new component for that called `AccountForm` within the `app/accou
import { useCallback, useEffect, useState } from 'react'
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'
-export default function AccountForm({ session }) {
+export default function AccountForm({ user }) {
const supabase = createClientComponentClient()
const [loading, setLoading] = useState(true)
const [fullname, setFullname] = useState(null)
const [username, setUsername] = useState(null)
const [website, setWebsite] = useState(null)
const [avatar_url, setAvatarUrl] = useState(null)
- const user = session?.user
const getProfile = useCallback(async () => {
try {
@@ -492,7 +491,7 @@ export default function AccountForm({ session }) {
<div className="form-widget">
<div>
<label htmlFor="email">Email</label>
- <input id="email" type="text" value={session?.user.email} disabled />
+ <input id="email" type="text" value={user?.email} disabled />
</div>
<div>
<label htmlFor="fullName">Full Name</label>
@@ -551,16 +550,15 @@ export default function AccountForm({ session }) {
'use client'
import { useCallback, useEffect, useState } from 'react'
import { Database } from '../database.types'
-import { Session, createClientComponentClient } from '@supabase/auth-helpers-nextjs'
+import { User, createClientComponentClient } from '@supabase/auth-helpers-nextjs'
-export default function AccountForm({ session }: { session: Session | null }) {
+export default function AccountForm({ user }: { user: User | null }) {
const supabase = createClientComponentClient<Database>()
const [loading, setLoading] = useState(true)
const [fullname, setFullname] = useState<string | null>(null)
const [username, setUsername] = useState<string | null>(null)
const [website, setWebsite] = useState<string | null>(null)
const [avatar_url, setAvatarUrl] = useState<string | null>(null)
- const user = session?.user
const getProfile = useCallback(async () => {
try {
@@ -627,7 +625,7 @@ export default function AccountForm({ session }: { session: Session | null }) {
<div className="form-widget">
<div>
<label htmlFor="email">Email</label>
- <input id="email" type="text" value={session?.user.email} disabled />
+ <input id="email" type="text" value={user?.email} disabled />
</div>
<div>
<label htmlFor="fullName">Full Name</label>
@@ -703,10 +701,10 @@ export default async function Account() {
const supabase = createServerComponentClient({ cookies: () => cookieStore })
const {
- data: { session },
- } = await supabase.auth.getSession()
+ data: { user },
+ } = await supabase.auth.getUser()
- return <AccountForm session={session} />
+ return <AccountForm user={user} />
}
```
@@ -723,10 +721,10 @@ export default async function Account() {
const supabase = createServerComponentClient<Database>({ cookies })
const {
- data: { session },
- } = await supabase.auth.getSession()
+ data: { user },
+ } = await supabase.auth.getUser()
- return <AccountForm session={session} />
+ return <AccountForm user={user} />
}
```
diff --git a/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx b/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx
index 0b4b80c6f53..3841390110e 100644
--- a/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx
+++ b/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx
@@ -92,6 +92,10 @@ export const handle: Handle = async ({ event, resolve }) => {
}
```
+<GetSessionWarning />
+
+In this case, the session information from `getSession` is supplied to the Supabase client so it can retrieve the auth token. This is safe, since the auth token signature will be revalidated on the Auth server. But you shouldn't trust the unsigned data that is stored alongside the JWT.
+
If you are using TypeScript the compiler might complain about `event.locals.supabase` and `event.locals.getSession`, this can be fixed by updating your `src/app.d.ts` with the content below:
```ts src/app.d.ts
diff --git a/apps/docs/pages/learn/auth-deep-dive/auth-policies.mdx b/apps/docs/pages/learn/auth-deep-dive/auth-policies.mdx
index a1c14b62e46..01c1ea5fbaa 100644
--- a/apps/docs/pages/learn/auth-deep-dive/auth-policies.mdx
+++ b/apps/docs/pages/learn/auth-deep-dive/auth-policies.mdx
@@ -96,6 +96,8 @@ If supabase-js is loaded on your site (in this case http://localhost:3000) it au
console.log(supabase.auth.getSession())
```
+<GetSessionWarning />
+
Now that we can use methods to issue JWTs to users, we want to start fetching resources specific to that user. So let's make some. Go to the SQL editor and run:
```sql
diff --git a/apps/docs/spec/supabase_js_v2.yml b/apps/docs/spec/supabase_js_v2.yml
index b830db46472..17888c051dc 100644
--- a/apps/docs/spec/supabase_js_v2.yml
+++ b/apps/docs/spec/supabase_js_v2.yml
@@ -738,6 +738,8 @@ functions:
$ref: '@supabase/gotrue-js.GoTrueClient.getSession'
notes: |
- This method retrieves the current local session (i.e local storage).
+ - The session contains a signed JWT and unencoded session data.
+ - Since the unencoded session data is retrieved from the local storage medium, **do not** rely on it as a source of trusted data on the server. It could be tampered with by the sender. If you need verified, trustworthy user data, call [`getUser`](/docs/reference/javascript/auth-getuser) instead.
- If the session has an expired access token, this method will use the refresh token to get a new session.
examples:
- id: get-the-session-data
diff --git a/packages/ui/src/components/Admonition/index.tsx b/packages/ui/src/components/Admonition/index.tsx
index 80e0fd6dd7a..a9a029e6223 100644
--- a/packages/ui/src/components/Admonition/index.tsx
+++ b/packages/ui/src/components/Admonition/index.tsx
@@ -100,7 +100,9 @@ export const Admonition = ({
)}
</>
) : (
- <div className="text mt [&_p]:mb-1.5 [&_p]:mt-0 mt-0.5 [&_p]:last:mb-0">{children}</div>
+ <div className="text mt [&_p]:mb-1.5 [&_p]:mt-0 mt-0.5 [&_p:last-child]:mb-0">
+ {children}
+ </div>
)}
</Alert>
)