Skip to content

Commit ba48f88

Browse files
authored
Add changes to gear up for deployment (#31)
* Add redirect for SPA routes * Only build src code in backend * Add Dockerfile and docker build step * Only add redirect route for prod or dev * Changes for deployment
1 parent 834d263 commit ba48f88

File tree

7 files changed

+190
-38
lines changed

7 files changed

+190
-38
lines changed

.github/workflows/pipeline.yml

+24-33
Original file line numberDiff line numberDiff line change
@@ -67,39 +67,33 @@ jobs:
6767
start: npm run server:test, npm start
6868
wait-on: 'http://localhost:3001/health, http://localhost:3000'
6969
working-directory: ./frontend
70-
71-
build:
72-
runs-on: ubuntu-20.04
73-
defaults:
74-
run:
75-
working-directory: backend
76-
needs: [test_lint_backend, test_lint_frontend]
77-
steps:
78-
- uses: actions/checkout@v3
79-
- uses: actions/setup-node@v2
80-
with:
81-
node-version: '16'
82-
- name: npm install
83-
run: npm install
84-
- name: install frontend dependencies
85-
run: cd ../frontend && npm install
86-
- name: build ui
87-
run: npm run build:ui
8870
deploy:
8971
if: ${{ github.ref == 'refs/head/main' }}
72+
needs: [test_lint_backend, test_lint_frontend]
9073
runs-on: ubuntu-20.04
91-
needs: [build]
9274
steps:
93-
- uses: actions/checkout@v2
94-
- uses: akhileshns/[email protected]
95-
with:
96-
heroku_api_key: ${{secrets.HEROKU_API_KEY}}
97-
heroku_app_name: "instaclone-sc"
98-
heroku_email: "[email protected]"
99-
appdir: "backend"
100-
healthcheck: ""
101-
checkstring: "ok"
102-
rollbackonhealthcheckfailed: true
75+
- uses: actions/checkout@v2
76+
- name: Login to Heroku Container registry
77+
env:
78+
HEROKU_API_KEY: ${{ secrets.HEROKU_API_KEY }}
79+
run: heroku container:login
80+
- name: Set Heroku Config Vars
81+
env:
82+
HEROKU_API_KEY: ${{ secrets.HEROKU_API_KEY }}
83+
run: |
84+
heroku config:set JWT_SECRET=${{ secrets.JWT_SECRET }} -a instaclone
85+
heroku config:set CLOUDINARY_API_SECRET=${{ secrets.CLOUDINARY_API_SECRET }} -a instaclone
86+
heroku config:set CLOUDINARY_API_KEY=${{ secrets.CLOUDINARY_API_KEY }} -a instaclone
87+
heroku config:set CLOUDINARY_NAME=${{ secrets.CLOUDINARY_NAME }} -a instaclone
88+
heroku config:set PROD_MONGODB_URI=${{ secrets.PROD_MONGODB_URI }} -a instaclone
89+
- name: Build and push
90+
env:
91+
HEROKU_API_KEY: ${{ secrets.HEROKU_API_KEY }}
92+
run: heroku container:push -a instaclone web
93+
- name: Release
94+
env:
95+
HEROKU_API_KEY: ${{ secrets.HEROKU_API_KEY }}
96+
run: heroku container:release -a instaclone web
10397
tag_release:
10498
if: ${{ github.ref == 'refs/head/main' }}
10599
needs: [deploy]
@@ -111,7 +105,4 @@ jobs:
111105
- name: Bump version and push tag
112106
uses: anothrNick/[email protected]
113107
env:
114-
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
115-
116-
# for deploying, make sure to have all final dependencies installed before deploying at all. aka, don't deploy, realize you need a new dep and then deploy again
117-
# todo: research how i can add new packages after deployment and then redeploy
108+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Dockerfile

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# BUILD STAGE
2+
3+
FROM node:16 as build-stage
4+
WORKDIR /app
5+
6+
# copying the all the frontend and backend code
7+
COPY frontend ./frontend
8+
COPY backend ./backend
9+
10+
# installing the frontend and backend dependencies
11+
RUN cd frontend && npm install
12+
RUN cd backend && npm install
13+
14+
# building the frontend UI from the backend
15+
RUN cd backend && npm run build:ui
16+
17+
# compiling TypeScript code
18+
RUN cd backend && npm run tsc
19+
20+
# RUN STAGE
21+
22+
FROM node:16 as run-stage
23+
WORKDIR /app
24+
25+
# copying the built frontend and backend code
26+
COPY --from=build-stage /app/backend/build /app
27+
28+
# copying the backend package.json
29+
COPY --from=build-stage /app/backend/package.json /app
30+
31+
# Installing the backend dependencies
32+
RUN npm install --omit=dev
33+
34+
EXPOSE 3001
35+
36+
CMD ["node", "index.js"]

backend/package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44
"description": "Backend for Instaclone",
55
"main": "index.js",
66
"scripts": {
7-
"tsc": "tsc",
7+
"tsc": "tsc -p tsconfig.build.json",
88
"ts-jest:init": "npx ts-jest config:init",
99
"test": "cross-env NODE_ENV=test jest --verbose --detectOpenHandles",
10-
"start": "cross-env NODE_ENV=production node src/index.ts",
10+
"start": "cross-env NODE_ENV=production node build/src/index.js",
1111
"dev": "cross-env NODE_ENV=development nodemon --files src/index.ts",
1212
"start:test": "cross-env NODE_ENV=test ts-node --files src/index.ts",
1313
"start:cypress-test": "cross-env NODE_ENV=cypress ts-node --files src/index.ts",

backend/src/app.ts

+20-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import express from 'express';
22
import cors from 'cors';
33
import morgan from 'morgan';
44
import cookieParser from 'cookie-parser';
5+
import path from 'path';
56
import mongodbConnect, { testMongodb } from './mongo';
67
import config from './utils/config';
78
import postRouter from './routes/posts';
@@ -15,8 +16,16 @@ import { errorHandler, logErrorCodes } from './utils/middleware';
1516
const { NODE_ENV } = process.env;
1617
const app = express();
1718

18-
if (NODE_ENV === 'development') {
19-
mongodbConnect(config.DEV_MONGODB_URI!);
19+
if (NODE_ENV === 'production' || NODE_ENV === 'development') {
20+
const mongodbUri = NODE_ENV === 'production'
21+
? config.PROD_MONGODB_URI
22+
: config.DEV_MONGODB_URI;
23+
24+
if (!mongodbUri) {
25+
throw new Error(`The ${NODE_ENV} MongoDB URI is not defined.`);
26+
}
27+
28+
mongodbConnect(mongodbUri);
2029
} else if (NODE_ENV === 'cypress') {
2130
(async () => {
2231
await testMongodb.connect();
@@ -42,6 +51,15 @@ app.use('/api/auth', authRouter);
4251
app.use('/api/likes', likeRouter);
4352
app.use('/api/notifications', notificationRouter);
4453

54+
if (NODE_ENV === ('production' || 'development')) {
55+
app.get('*', (_req, res) => {
56+
const prodPath = path.join(__dirname, 'index.html');
57+
const devPath = path.join(__dirname, '..', 'build', 'index.html');
58+
59+
res.sendFile(NODE_ENV === 'production' ? prodPath : devPath);
60+
});
61+
}
62+
4563
if (NODE_ENV !== 'production') {
4664
app.use('/api/test', testRouter);
4765
}

backend/src/mongo/index.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import mongoose from 'mongoose';
22
import logger from '../utils/logger';
33

4+
const { NODE_ENV } = process.env;
5+
46
const connect = async (uri: string) => {
57
try {
68
await mongoose.connect(uri);
79
logger.info('Connected to: ', uri);
810
} catch (error) {
911
const message = logger.getErrorMessage(error);
10-
logger.error('Error connecting to dev MongoDB: ', message);
12+
logger.error(`Error connecting to ${NODE_ENV} MongoDB: `, message);
1113
}
1214
};
1315

backend/src/utils/config.ts

+2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ require('dotenv').config();
22

33
const {
44
DEV_MONGODB_URI,
5+
PROD_MONGODB_URI,
56
PORT,
67
CLOUDINARY_NAME,
78
CLOUDINARY_API_KEY,
@@ -16,4 +17,5 @@ export default {
1617
CLOUDINARY_API_KEY,
1718
CLOUDINARY_API_SECRET,
1819
JWT_SECRET,
20+
PROD_MONGODB_URI,
1921
};

backend/tsconfig.build.json

+103
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
{
2+
"compilerOptions": {
3+
/* Visit https://aka.ms/tsconfig.json to read more about this file */
4+
5+
/* Projects */
6+
// "incremental": true, /* Enable incremental compilation */
7+
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8+
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
9+
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
10+
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11+
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12+
13+
/* Language and Environment */
14+
"target": "ES2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15+
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16+
// "jsx": "preserve", /* Specify what JSX code is generated. */
17+
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18+
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19+
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
20+
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21+
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
22+
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
23+
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24+
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25+
26+
/* Modules */
27+
"module": "commonjs", /* Specify what module code is generated. */
28+
// "rootDir": "./", /* Specify the root folder within your source files. */
29+
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
30+
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
31+
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
32+
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
33+
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
34+
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
35+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
36+
// "resolveJsonModule": true, /* Enable importing .json files */
37+
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
38+
39+
/* JavaScript Support */
40+
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
41+
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
42+
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
43+
44+
/* Emit */
45+
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
46+
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
47+
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
48+
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
49+
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
50+
"outDir": "./build/", /* Specify an output folder for all emitted files. */
51+
// "removeComments": true, /* Disable emitting comments. */
52+
// "noEmit": true, /* Disable emitting files from a compilation. */
53+
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
54+
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
55+
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
56+
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
57+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
58+
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
59+
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
60+
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
61+
// "newLine": "crlf", /* Set the newline character for emitting files. */
62+
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
63+
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
64+
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
65+
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
66+
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
67+
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
68+
69+
/* Interop Constraints */
70+
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
71+
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
72+
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
73+
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
74+
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
75+
76+
/* Type Checking */
77+
"strict": true, /* Enable all strict type-checking options. */
78+
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
79+
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
80+
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
81+
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
82+
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
83+
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
84+
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
85+
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
86+
"noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
87+
"noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
88+
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
89+
"noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
90+
"noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
91+
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
92+
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
93+
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
94+
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
95+
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
96+
97+
/* Completeness */
98+
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
99+
"skipLibCheck": true, /* Skip type checking all .d.ts files. */
100+
"typeRoots": ["./node_modules/@types", "./src/typings"]
101+
},
102+
"include": ["src/**/*.ts"],
103+
}

0 commit comments

Comments
 (0)