Skip to content

Commit

Permalink
feat: use cloudflare env only & modify dev proxy plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
aube-dev committed Sep 4, 2024
1 parent 89377ab commit fb4c64b
Show file tree
Hide file tree
Showing 21 changed files with 627 additions and 251 deletions.
19 changes: 11 additions & 8 deletions app/components/KakaoLoginButton/KakaoLoginButton.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import React, { useMemo } from 'react';
import React, { useEffect, useState } from 'react';
import useEnv from '@/hooks/useEnv';
import { getUUID } from '@/utils/random';

const clientId = 'f5aa2f20e42d783654b8e8c01bfc6312';
//redirectUri는 등록된 redirectUri중에 임의로 사용했습니다.
const redirectUri = 'http://localhost:5173/oauth/kakao';

const KakaoLoginButton: React.FC = () => {
const kakaoAuthUrl = useMemo(() => {
const env = useEnv();
const [kakaoAuthUrl, setKakaoAuthUrl] = useState('');

useEffect(() => {
const userUUID = getUUID();
return `https://kauth.kakao.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code&state=${userUUID}`;
}, []);
const redirectUri = window.location.origin + '/oauth/kakao';
setKakaoAuthUrl(
`https://kauth.kakao.com/oauth/authorize?client_id=${env.KAKAO_CLIENT_ID}&redirect_uri=${redirectUri}&response_type=code&state=${userUUID}`,
);
}, [env.KAKAO_CLIENT_ID]);

return (
<a href={kakaoAuthUrl}>
Expand Down
4 changes: 4 additions & 0 deletions app/contexts/EnvContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { createContext } from 'react';
import { type ClientEnv } from '@server/constants/env';

export const EnvContext = createContext<ClientEnv | null>(null);
21 changes: 21 additions & 0 deletions app/hooks/useEnv.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useContext } from 'react';
import { EnvContext } from '@/contexts/EnvContext';
import { type ClientEnv, clientEnvSchema } from '@server/constants/env';

/**
* 클라이언트용 환경 변수를 얻는 hook
* @example
* ```
* const env = useEnv();
* console.log(env.KAKAO_CLIENT_ID);
* ```
*/
const useEnv = (): ClientEnv => {
const envFromContext = useContext(EnvContext);

const env = clientEnvSchema.parse(envFromContext);

return env;
};

export default useEnv;
45 changes: 28 additions & 17 deletions app/root.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,42 @@
import { json, type LoaderFunctionArgs } from '@remix-run/cloudflare';
import {
Links,
Meta,
Outlet,
Scripts,
ScrollRestoration,
useLoaderData,
} from '@remix-run/react';
import { type ReactNode } from 'react';
import { EnvContext } from '@/contexts/EnvContext';

import './root.css';
import '@/styles/theme.css';

export const Layout = ({ children }: { children: ReactNode }) => (
<html lang="ko">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
</body>
</html>
);
export const loader = async (args: LoaderFunctionArgs) =>
json({
env: args.context.clientEnv,
});

const App = () => <Outlet />;
const App = () => {
const data = useLoaderData<typeof loader>();

return (
<html lang="ko">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<body>
<EnvContext.Provider value={data.env}>
<Outlet />
</EnvContext.Provider>
<ScrollRestoration />
<Scripts />
</body>
</html>
);
};

export default App;
15 changes: 15 additions & 0 deletions app/routes/oauth.kakao.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { type LoaderFunctionArgs } from '@remix-run/cloudflare';

export const loader = async ({ request }: LoaderFunctionArgs) => {
const url = new URL(request.url);
const code = url.searchParams.get('code');
const state = url.searchParams.get('state');

console.log(code, state);

return null;
};

const KakaoRedirect = () => <div>카카오 로그인 중...</div>;

export default KakaoRedirect;
18 changes: 0 additions & 18 deletions app/routes/oauth.kakao.tsx.tsx

This file was deleted.

9 changes: 0 additions & 9 deletions app/vite-env.d.ts

This file was deleted.

55 changes: 15 additions & 40 deletions functions/[[path]].ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,34 @@
import {
createWorkersKVSessionStorage,
createCookie,
} from '@remix-run/cloudflare';
import { createPagesFunctionHandler } from '@remix-run/cloudflare-pages';
import type { FetchApi } from '@/constants/types/api';
import type { AuthSession, AuthSessionData } from '@/constants/types/auth';
import { fetchApi } from '@/utils/api.server';
import {
clientEnvSchema,
type ContextEnv,
serverEnvSchema,
} from '@server/constants/env';
import { getLoadContext, makeAuthSession } from '@server/utils/cloudflare';

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - the server build file is generated by `remix vite:build`
// eslint-disable-next-line import/no-unresolved, import/order
import * as build from '../build/server';

type ContextEnv = {
readonly KV_NAMESPACE: KVNamespace<string>;
readonly AUTH_COOKIE_SESSION_SECRET: string;
readonly API_URL: string;
};

declare module '@remix-run/cloudflare' {
interface AppLoadContext extends ContextEnv {
authSession: AuthSession;
fetchApi: FetchApi;
}
}

export const onRequest = async (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
context: EventContext<ContextEnv, any, any>,
): Promise<Response> => {
const authSessionCookie = createCookie('__auth_session', {
secrets: [context.env.AUTH_COOKIE_SESSION_SECRET],
sameSite: true,
});
const authSessionStorage = createWorkersKVSessionStorage<AuthSessionData>({
cookie: authSessionCookie,
kv: context.env.KV_NAMESPACE,
});
const authSession = await authSessionStorage.getSession(
clientEnvSchema.parse(context.env);
serverEnvSchema.parse(context.env);

const { authSessionStorage, authSession } = await makeAuthSession(
{
authCookieSessionSecret: context.env.AUTH_COOKIE_SESSION_SECRET,
kvNamespace: context.env.KV_NAMESPACE,
},
context.request.headers.get('Cookie'),
);

const handleRequest = createPagesFunctionHandler<ContextEnv>({
build,
getLoadContext: ({ context: loadContext }) => ({
...loadContext.cloudflare.env,
authSession,
fetchApi: async (apiInfo, variables) =>
fetchApi(
apiInfo,
variables,
loadContext.cloudflare.env.API_URL,
authSession,
),
}),
getLoadContext: (args) => getLoadContext(authSession, args),
});

const response = await handleRequest(context);
Expand Down
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"type": "module",
"scripts": {
"build": "remix vite:build",
"dev": "wrangler pages download config ort-web --force && remix vite:build && wrangler pages dev --live-reload ./build/client",
"dev": "wrangler pages download config ort-web --force && remix vite:dev",
"lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .",
"start": "remix-serve ./build/server/index.js",
"typecheck": "tsc",
Expand All @@ -24,12 +24,14 @@
"isbot": "4.4.0",
"react": "18.3.1",
"react-dom": "18.3.1",
"uuid": "10.0.0"
"uuid": "10.0.0",
"zod": "3.23.8"
},
"devDependencies": {
"@commitlint/cli": "19.3.0",
"@commitlint/config-conventional": "19.2.2",
"@remix-run/dev": "2.11.2",
"@remix-run/node": "2.11.2",
"@remix-run/testing": "2.11.2",
"@storybook/addon-essentials": "8.2.9",
"@storybook/addon-interactions": "8.2.9",
Expand All @@ -40,6 +42,7 @@
"@storybook/test": "8.2.9",
"@types/react": "18.3.3",
"@types/react-dom": "18.3.0",
"@types/set-cookie-parser": "2.4.10",
"@types/uuid": "10.0.0",
"@typescript-eslint/eslint-plugin": "7.16.0",
"@typescript-eslint/parser": "7.16.0",
Expand All @@ -56,6 +59,7 @@
"husky": "9.1.1",
"lint-staged": "15.2.7",
"prettier": "3.3.3",
"set-cookie-parser": "2.7.0",
"storybook": "8.2.9",
"typescript": "5.5.3",
"vite": "5.3.3",
Expand Down
Loading

0 comments on commit fb4c64b

Please sign in to comment.