Skip to content

Commit 678f327

Browse files
committed
Add Redirect An Unauthorized User as a Next.js TIL
1 parent ff2f363 commit 678f327

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

Diff for: README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For 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

Diff for: nextjs/redirect-an-unauthorized-user.md

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
```

0 commit comments

Comments
 (0)