|
| 1 | +// Should be at the top of the file - used to load clerk secret key |
| 2 | +import * as dotenv from 'dotenv'; |
| 3 | +dotenv.config(); |
| 4 | + |
| 5 | +import { clerkClient } from '@clerk/clerk-sdk-node'; |
| 6 | +import express from 'express'; |
| 7 | +import ViteExpress from 'vite-express'; |
| 8 | + |
| 9 | +const app = express(); |
| 10 | + |
| 11 | +app.set('view engine', 'ejs'); |
| 12 | +app.set('views', 'src/views'); |
| 13 | + |
| 14 | +app.get('/api/protected', [clerkClient.expressRequireAuth() as any], (_req: any, res: any) => { |
| 15 | + res.send('Protected API response').end(); |
| 16 | +}); |
| 17 | + |
| 18 | +app.get('/sign-in', (_req: any, res: any) => { |
| 19 | + return res.render('sign-in.ejs', { |
| 20 | + publishableKey: process.env.VITE_CLERK_PUBLISHABLE_KEY, |
| 21 | + signInUrl: process.env.CLERK_SIGN_IN_URL, |
| 22 | + }); |
| 23 | +}); |
| 24 | + |
| 25 | +app.get('/', (_req: any, res: any) => { |
| 26 | + return res.render('index.ejs', { |
| 27 | + publishableKey: process.env.VITE_CLERK_PUBLISHABLE_KEY, |
| 28 | + signInUrl: process.env.CLERK_SIGN_IN_URL, |
| 29 | + }); |
| 30 | +}); |
| 31 | + |
| 32 | +app.get('/sign-up', (_req: any, res: any) => { |
| 33 | + return res.render('sign-up.ejs', { |
| 34 | + publishableKey: process.env.VITE_CLERK_PUBLISHABLE_KEY, |
| 35 | + signUpUrl: process.env.CLERK_SIGN_UP_URL, |
| 36 | + }); |
| 37 | +}); |
| 38 | + |
| 39 | +app.get('/protected', (_req: any, res: any) => { |
| 40 | + return res.render('protected.ejs', { |
| 41 | + publishableKey: process.env.VITE_CLERK_PUBLISHABLE_KEY, |
| 42 | + signInUrl: process.env.CLERK_SIGN_IN_URL, |
| 43 | + signUpUrl: process.env.CLERK_SIGN_UP_URL, |
| 44 | + }); |
| 45 | +}); |
| 46 | + |
| 47 | +// Handle authentication error, otherwise application will crash |
| 48 | +// @ts-ignore |
| 49 | +app.use((err, req, res, next) => { |
| 50 | + if (err) { |
| 51 | + console.error(err); |
| 52 | + res.status(401).end(); |
| 53 | + return; |
| 54 | + } |
| 55 | + |
| 56 | + return next(); |
| 57 | +}); |
| 58 | + |
| 59 | +const port = parseInt(process.env.PORT as string) || 3002; |
| 60 | +ViteExpress.listen(app, port, () => console.log(`Server is listening on port ${port}...`)); |
0 commit comments