@mikandev/next-discord-auth 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # next-discord-auth
2
+
3
+ To install dependencies:
4
+
5
+ ```bash
6
+ bun install
7
+ ```
8
+
9
+ To run:
10
+
11
+ ```bash
12
+ bun run index.ts
13
+ ```
14
+
15
+ This project was created using `bun init` in bun v1.2.8. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@mikandev/next-discord-auth",
3
+ "module": "dist/index.ts",
4
+ "types": "dist/index.d.ts",
5
+ "version": "0.0.1",
6
+ "type": "module",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "format": "biome format --write ."
10
+ },
11
+ "devDependencies": {
12
+ "@biomejs/biome": "^1.9.4",
13
+ "@types/bun": "latest",
14
+ "@types/jsonwebtoken": "^9.0.9"
15
+ },
16
+ "peerDependencies": {
17
+ "typescript": "^5"
18
+ },
19
+ "dependencies": {
20
+ "jsonwebtoken": "^9.0.2",
21
+ "next": "^15.3.2"
22
+ }
23
+ }
package/src/index.ts ADDED
@@ -0,0 +1,17 @@
1
+ export interface Session {
2
+ user: {
3
+ id: string;
4
+ name: string;
5
+ email: string | null;
6
+ avatar: string;
7
+ }
8
+ expires: string;
9
+ }
10
+
11
+ export interface Config {
12
+ clientId: string;
13
+ clientSecret: string;
14
+ scopes: string[];
15
+ redirectUri: string;
16
+ jwtSecret: string;
17
+ }
@@ -0,0 +1,35 @@
1
+ import type { Config } from '../index';
2
+
3
+ export const ExchangeCodeForTokens = async (config: Config, code: string) => {
4
+ const response = await fetch('https://discord.com/api/oauth2/token', {
5
+ method: 'POST',
6
+ headers: {
7
+ 'Content-Type': 'application/x-www-form-urlencoded',
8
+ },
9
+ body: new URLSearchParams({
10
+ client_id: config.clientId,
11
+ client_secret: config.clientSecret,
12
+ grant_type: 'authorization_code',
13
+ code: code,
14
+ redirect_uri: config.redirectUri,
15
+ scope: config.scopes.join(' '),
16
+ }),
17
+ });
18
+
19
+ if (!response.ok) {
20
+ const error = await response.json() as { error_description?: string; message?: string };
21
+ throw new Error(`Failed to exchange code for token: ${error.error_description || error.message}`);
22
+ }
23
+
24
+ const data = await response.json() as {
25
+ access_token: string;
26
+ refresh_token: string;
27
+ expires_in: number;
28
+ };
29
+
30
+ return {
31
+ accessToken: data.access_token,
32
+ refreshToken: data.refresh_token,
33
+ expiresIn: data.expires_in,
34
+ };
35
+ };
@@ -0,0 +1,52 @@
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import type { Session, Config } from "./index";
3
+ import { cookies } from "next/headers";
4
+ import { ExchangeCodeForTokens } from "./lib/oauth";
5
+ import jwt from "jsonwebtoken";
6
+
7
+ export const handleRedirect = async (config: Config, req: NextRequest) => {
8
+ const cookieStore = await cookies();
9
+ const params = new URL(req.url).searchParams;
10
+ const code = params.get("code");
11
+
12
+ if (!code) {
13
+ return NextResponse.json({error: "Authorization code not found"}, {status: 400});
14
+ }
15
+
16
+ const response = await ExchangeCodeForTokens(config, code);
17
+
18
+ const sessionData = await fetch('https://discord.com/api/users/@me', {
19
+ headers: {
20
+ 'Authorization': `Bearer ${response.accessToken}`,
21
+ },
22
+ });
23
+
24
+ if (!sessionData.ok) {
25
+ const error = await sessionData.json() as { error?: string; message?: string };
26
+ return NextResponse.json({error: error.message || "Failed to fetch user data"}, {status: 500});
27
+ }
28
+
29
+ const userData = await sessionData.json() as {
30
+ user: {
31
+ id: string;
32
+ username: string;
33
+ discriminator: string;
34
+ avatar: string | null;
35
+ email?: string;
36
+ }
37
+ };
38
+
39
+ const session: Session = {
40
+ user: {
41
+ id: userData.user.id,
42
+ name: `${userData.user.username}#${userData.user.discriminator}`,
43
+ email: userData.user.email || null,
44
+ avatar: `https://cdn.discordapp.com/avatars/${userData.user.id}/${userData.user.avatar}.png`,
45
+ },
46
+ expires: new Date(Date.now() + response.expiresIn * 1000).toISOString(),
47
+ };
48
+
49
+ const token = jwt.sign(session, config.jwtSecret, { expiresIn: response.expiresIn });
50
+
51
+ await cookieStore.set("AUTH_SESSION", token);
52
+ }
@@ -0,0 +1,18 @@
1
+ import type { NextRequest, NextResponse } from "next/server";
2
+ import type { Session, Config } from "./index";
3
+ import jwt from "jsonwebtoken";
4
+
5
+ export const getSession = async (config: Config, req: NextRequest): Promise<Session | null> => {
6
+ const token = req.cookies.get("AUTH_SESSION")?.value;
7
+ if (!token) {
8
+ return null;
9
+ }
10
+
11
+ try {
12
+ const decoded = jwt.verify(token, config.jwtSecret) as Session;
13
+ return decoded;
14
+ } catch (error) {
15
+ console.error("Invalid token:", error);
16
+ return null;
17
+ }
18
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "compilerOptions": {
3
+ // Environment setup & latest features
4
+ "lib": ["ESNext"],
5
+ "target": "ESNext",
6
+ "module": "ESNext",
7
+ "moduleDetection": "force",
8
+ "jsx": "react-jsx",
9
+ "allowJs": true,
10
+ "outDir": "./dist",
11
+ "rootDir": "./src",
12
+
13
+ // Bundler mode
14
+ "moduleResolution": "bundler",
15
+ "verbatimModuleSyntax": true,
16
+
17
+ // Best practices
18
+ "strict": true,
19
+ "skipLibCheck": true,
20
+ "noFallthroughCasesInSwitch": true,
21
+ "noUncheckedIndexedAccess": true,
22
+
23
+ // Some stricter flags (disabled by default)
24
+ "noUnusedLocals": false,
25
+ "noUnusedParameters": false,
26
+ "noPropertyAccessFromIndexSignature": false
27
+ }
28
+ }