Skip to content

Commit af28db1

Browse files
authored
chore: update middleware (#247)
* chore: update middleware and README. * chore: changeset
1 parent ab20d8f commit af28db1

File tree

5 files changed

+51
-42
lines changed

5 files changed

+51
-42
lines changed

.changeset/serious-snakes-wave.md

Lines changed: 0 additions & 7 deletions
This file was deleted.

.changeset/tiny-crabs-share.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@supabase/auth-helpers-nextjs': patch
3+
---
4+
5+
chore: export middleware at root.

examples/nextjs/middleware.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { withMiddlewareAuth } from '@supabase/auth-helpers-nextjs/dist/middleware';
1+
import { withMiddlewareAuth } from '@supabase/auth-helpers-nextjs';
22

33
export const middleware = withMiddlewareAuth({
44
redirectTo: '/',

packages/nextjs/README.md

Lines changed: 44 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -42,39 +42,35 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
4242

4343
### Basic Setup
4444

45-
- Create an `auth` directory under the `/pages/api/` directory.
46-
47-
- Create a `[...supabase].js` file under the newly created `auth` directory.
48-
49-
The path to your dynamic API route file would be `/pages/api/auth/[...supabase].js`. Populate that file as follows:
50-
51-
```js
52-
import { handleAuth } from '@supabase/auth-helpers-nextjs';
53-
54-
export default handleAuth({ logout: { returnTo: '/' } });
55-
```
56-
57-
Executing `handleAuth()` creates the following route handlers under the hood that perform different parts of the authentication flow:
58-
59-
- `/api/auth/callback`: The `UserProvider` forwards the session details here every time `onAuthStateChange` fires on the client side. This is needed to set up the cookies for your application so that SSR works seamlessly.
60-
61-
- `/api/auth/user`: You can fetch user profile information in JSON format.
62-
63-
- `/api/auth/logout`: Your Next.js application logs out the user. You can optionally pass a `returnTo` parameter to return to a custom relative URL after logout, eg `/api/auth/logout?returnTo=/login`. This will overwrite the logout `returnTo` option specified `handleAuth()`
64-
6545
Wrap your `pages/_app.js` component with the `UserProvider` component:
6646

6747
```jsx
6848
// pages/_app.js
6949
import React from 'react';
70-
import { UserProvider } from '@supabase/auth-helpers-react';
71-
import { supabaseClient } from '@supabase/auth-helpers-nextjs';
50+
import { useRouter } from 'next/router';
51+
import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs';
52+
import { SessionContextProvider } from '@supabase/auth-helpers-react';
53+
54+
function MyApp({ Component, pageProps }: AppProps) {
55+
const router = useRouter();
56+
const [supabaseClient] = useState(() => createBrowserSupabaseClient());
7257

73-
export default function App({ Component, pageProps }) {
7458
return (
75-
<UserProvider supabaseClient={supabaseClient}>
59+
<SessionContextProvider
60+
supabaseClient={supabaseClient}
61+
initialSession={pageProps.initialSession}
62+
>
63+
<button
64+
onClick={async () => {
65+
await supabaseClient.auth.signOut();
66+
router.push('/');
67+
}}
68+
>
69+
Logout
70+
</button>
71+
7672
<Component {...pageProps} />
77-
</UserProvider>
73+
</SessionContextProvider>
7874
);
7975
}
8076
```
@@ -83,15 +79,16 @@ You can now determine if a user is authenticated by checking that the `user` obj
8379

8480
## Client-side data fetching with RLS
8581

86-
For [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) to work properly when fetching data client-side, you need to make sure to import the `{ supabaseClient }` from `# @supabase/auth-helpers-nextjs` and only run your query once the user is defined client-side in the `useUser()` hook:
82+
For [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) to work properly when fetching data client-side, you need to make sure to use the `supabaseClient` from the `useSessionContext` hook and only run your query once the user is defined client-side in the `useUser()` hook:
8783

8884
```js
89-
import { Auth } from '@supabase/auth-ui-react';
90-
import { useUser } from '@supabase/auth-helpers-react';
85+
import { Auth, ThemeSupa } from '@supabase/auth-ui-react';
86+
import { useUser, useSessionContext } from '@supabase/auth-helpers-react';
9187
import { supabaseClient } from '@supabase/auth-helpers-nextjs';
9288
import { useEffect, useState } from 'react';
9389

9490
const LoginPage = () => {
91+
const { isLoading, session, error, supabaseClient } = useSessionContext();
9592
const { user, error } = useUser();
9693
const [data, setData] = useState();
9794

@@ -109,10 +106,11 @@ const LoginPage = () => {
109106
<>
110107
{error && <p>{error.message}</p>}
111108
<Auth
109+
redirectTo="http://localhost:3000/"
110+
appearance={{ theme: ThemeSupa }}
112111
supabaseClient={supabaseClient}
113112
providers={['google', 'github']}
114113
socialLayout="horizontal"
115-
socialButtonSize="xlarge"
116114
/>
117115
</>
118116
);
@@ -273,20 +271,24 @@ If you visit `/api/protected-route` without a valid session cookie, you will get
273271
274272
## Protecting routes with [Nextjs Middleware](https://nextjs.org/docs/middleware)
275273
276-
As an alternative to protecting individual pages using `getServerSideProps` with `withPageAuth`, `withMiddlewareAuth` can be used from inside a `_middleware` file to protect an entire directory. In the following example, all requests to `/protected/*` will check whether a user is signed in, if successful the request will be forwarded to the destination route, otherwise the user will be redirected to `/login` (defaults to: `/`) with a 307 Temporary Redirect response status:
274+
As an alternative to protecting individual pages using `getServerSideProps` with `withPageAuth`, `withMiddlewareAuth` can be used from inside a `middleware` file to protect the entire directory or those that match the config object. In the following example, all requests to `/middleware-protected/*` will check whether a user is signed in, if successful the request will be forwarded to the destination route, otherwise the user will be redirected to `/login` (defaults to: `/`) with a 307 Temporary Redirect response status:
277275
278276
```ts
279-
// pages/protected/_middleware.ts
280-
import { withMiddlewareAuth } from '@supabase/auth-helpers-nextjs/middleware';
277+
// middleware.ts
278+
import { withMiddlewareAuth } from '@supabase/auth-helpers-nextjs';
281279
282280
export const middleware = withMiddlewareAuth({ redirectTo: '/login' });
281+
282+
export const config = {
283+
matcher: ['/middleware-protected/:path*']
284+
};
283285
```
284286
285287
It is also possible to add finer granularity based on the user logged in. I.e. you can specify a promise to determine if a specific user has permission or not.
286288
287289
```ts
288-
// pages/protected/_middleware.ts
289-
import { withMiddlewareAuth } from '@supabase/auth-helpers-nextjs/dist/middleware';
290+
// middleware.ts
291+
import { withMiddlewareAuth } from '@supabase/auth-helpers-nextjs';
290292
291293
export const middleware = withMiddlewareAuth({
292294
redirectTo: '/login',
@@ -295,8 +297,16 @@ export const middleware = withMiddlewareAuth({
295297
redirectTo: '/insufficient-permissions'
296298
}
297299
});
300+
301+
export const config = {
302+
matcher: ['/middleware-protected/:path*']
303+
};
298304
```
299305
306+
## Migrating from `0.2.X` to `0.3.X`/`0.4.X`
307+
308+
// TODO
309+
300310
## Migrating from @supabase/supabase-auth-helpers to @supabase/auth-helpers
301311
302312
This is a step by step guide on migrating away from the `@supabase/supabase-auth-helpers` to the newly released `@supabase/auth-helpers`.

packages/nextjs/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
export type { User } from '@supabase/supabase-js';
88

99
// Methods
10+
export * from './middleware';
1011
export { default as withPageAuth } from './utils/withPageAuth';
1112
export { default as withApiAuth } from './utils/withApiAuth';
1213
export { default as logger } from './utils/log';

0 commit comments

Comments
 (0)