File tree Expand file tree Collapse file tree 2 files changed +52
-1
lines changed Expand file tree Collapse file tree 2 files changed +52
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010
1111For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
1212
13- _ 1358 TILs and counting..._
13+ _ 1359 TILs and counting..._
1414
1515---
1616
@@ -592,6 +592,7 @@ _1358 TILs and counting..._
592592- [ Define URL Redirects In The Next Config] ( nextjs/define-url-redirects-in-the-next-config.md )
593593- [ Make Environment Variable Publicly Available] ( nextjs/make-environment-variable-publicly-available.md )
594594- [ Push A Route With A URL Object] ( nextjs/push-a-route-with-a-url-object.md )
595+ - [ Redirect An Unauthorized User] ( nextjs/redirect-an-unauthorized-user.md )
595596- [ Remove A Query Param From The URL] ( nextjs/remove-a-query-param-from-the-url.md )
596597- [ Ship Public Assets With A Next.js App] ( nextjs/ship-public-assets-with-a-nextjs-app.md )
597598
Original file line number Diff line number Diff line change 1+ # Redirect An Unauthorized User
2+
3+ With the Page Router in earlier next version, we could do a server-side
4+ authorization check in ` getServerSideProps ` and then return a
5+ [ ` redirect ` ] ( https://nextjs.org/docs/pages/api-reference/functions/get-server-side-props#redirect )
6+ response in order to redirect the user to a page they are authorized for.
7+
8+ That might look something like this:
9+
10+ ``` javascript
11+ export async function getServerSideProps (context ) {
12+ const session = await getServerAuthSession ()
13+ const ability = getAbility ({user: session? .user })
14+
15+ if (! ability .can (' create' , ' Post' )) {
16+ return {
17+ redirect: {
18+ destination: ' /posts' ,
19+ permanent: false ,
20+ },
21+ }
22+ }
23+
24+ return {
25+ props: {},
26+ }
27+ }
28+ ` ` `
29+
30+ We can achieve the same thing with the App Router, but with a bit less code.
31+ The ` next/ navigation` package has a [` redirect`
32+ function](https://nextjs.org/docs/app/api-reference/functions/redirect) that we
33+ can invoke directly in a component. This will redirect the user instead of
34+ rendering the component to HTML.
35+
36+ ` ` ` javascript
37+ import { redirect } from ' next/navigation'
38+
39+ export default async function CreatePost () {
40+ const session = await getServerAuthSession ()
41+ const ability = getAbility ({user: session? .user })
42+
43+ if (! ability .can (' create' , ' Post' )) {
44+ redirect (' /posts' )
45+ }
46+
47+ // JSX follows
48+ return (... )
49+ }
50+ ` ` `
You can’t perform that action at this time.
0 commit comments