Skip to content

Commit b5f3aca

Browse files
committed
Handle SSR check of JWT
1 parent 5826013 commit b5f3aca

1 file changed

Lines changed: 33 additions & 26 deletions

File tree

  • frontend/app/composables

frontend/app/composables/jwt.ts

Lines changed: 33 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,43 @@
1-
import type { User } from '@/types/user'
1+
import type {User} from '@/types/user'
22

33
export const useJwt = () => {
4-
const parseJwt = (token: string): User | undefined => {
5-
const base64Payload = token.split('.')[1]
4+
const parseJwt = (token: string): User | undefined => {
5+
const base64Payload = token.split('.')[1]
66

7-
if (base64Payload === undefined) {
8-
return undefined
9-
}
7+
if (base64Payload === undefined) {
8+
return undefined
9+
}
1010

11-
const base64 = base64Payload.replace(/-/g, '+').replace(/_/g, '/')
11+
const base64 = base64Payload.replace(/-/g, '+').replace(/_/g, '/')
1212

13-
const jsonPayload = decodeURIComponent(
14-
window
15-
.atob(base64)
16-
.split('')
17-
.map(function (c) {
18-
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
19-
})
20-
.join('')
21-
)
13+
let jsonPayload: string
2214

23-
const jsonUser = JSON.parse(jsonPayload)
15+
if (typeof window !== 'undefined') {
16+
// Running in browser
17+
jsonPayload = decodeURIComponent(
18+
window
19+
.atob(base64)
20+
.split('')
21+
.map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
22+
.join('')
23+
)
24+
} else {
25+
// Running in Node (SSR)
26+
const buffer = Buffer.from(base64, 'base64')
27+
jsonPayload = buffer.toString('utf-8')
28+
}
2429

25-
return {
26-
id: jsonUser['slack_id'],
27-
name: jsonUser['name'],
28-
avatar: jsonUser['avatar'],
29-
email: jsonUser['email'],
30+
const jsonUser = JSON.parse(jsonPayload)
31+
32+
return {
33+
id: jsonUser['slack_id'],
34+
name: jsonUser['name'],
35+
avatar: jsonUser['avatar'],
36+
email: jsonUser['email'],
37+
}
3038
}
31-
}
3239

33-
return {
34-
parseJwt,
35-
}
40+
return {
41+
parseJwt,
42+
}
3643
}

0 commit comments

Comments
 (0)