Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/cli/express #130

Merged
merged 12 commits into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [unreleased]

## [0.0.56] - 2024-12-12

- Adds changes to the express boilerplate to work as project scaffolding

porcellus marked this conversation as resolved.
Show resolved Hide resolved
## [0.0.55] - 2024-12-12

- Adds a Vite-based React implementation. To be used as reference implementation for front-end options.
Expand Down
18 changes: 18 additions & 0 deletions boilerplate/backend/node-express/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules

# production
/dist

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
66 changes: 66 additions & 0 deletions boilerplate/backend/node-express/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# SuperTokens + Express

A demo implementation of [SuperTokens](https://supertokens.com/) with [Express](https://expressjs.com/).

## General Info

This project aims to demonstrate how to integrate SuperTokens into an Express server. Its primary purpose is to serve as an educational tool, but it can also be used as a starting point for your own project.

## Repo Structure

### Source

```
📦backend
┣ 📜config.tsx --> Root component of the app
┗ 📜index.tsx --> Entry point of the app
```

#### SuperTokens

The full configuration needed for the SuperTokens' back-end to work is in the `src/config.tsx` file. This file will differ based on the [auth recipe](https://supertokens.com/docs/guides) you choose.

If you choose to use this as a starting point for your own project, you can further customize SuperTokens in the `src/config.tsx` file. Refer to our [docs](https://supertokens.com/docs) (and make sure to choose the correct recipe) for more details.

## Application Flow

When using SuperTokens, the front-end never calls directly to the SuperTokens Core, the service that creates and manages sessions. Instead, the front-end calls to the back-end and the back-end calls to the Core. You can read more about [how SuperTokens works here](https://supertokens.com/docs/thirdpartyemailpassword/architecture).

The back-end has two main files:

1. **Entry Point (`index.tsx`)**
porcellus marked this conversation as resolved.
Show resolved Hide resolved

- Initializes SuperTokens
- Adds CORS headers for sessions with the front-end
- Adds SuperTokens middleware
- Endpoints:
- `/hello`: Public route not protected by SuperTokens
- `/sessioninfo`: Uses SuperTokens middleware to pull the session token off the request and get the user session info
- `/tenants`: Grabs a list of tenants for multitenant configured applications

2. **Configuration (`config.ts`)**
- `supertokensConfig`:
- `supertokens`:
- `connectionURI`: Sets the URL that your SuperTokens core is located. By default, it connects to the playground core. In production, you can [host your own core](https://supertokens.com/docs/thirdpartyemailpassword/pre-built-ui/setup/core/with-docker) or create an account to [enable managed hosting](https://supertokens.com/dashboard-saas)
- `appInfo`: Holds informaiton like your project name
- `apiDomain`: Sets the domain your back-end API is on. SuperTokens automatically listens to create requests at `${apiDomain}/auth`
porcellus marked this conversation as resolved.
Show resolved Hide resolved
- `websiteDomain`: Sets the domain your front-end website is on
- `recipeList`: An array of recipes for adding supertokens features

## Additional resources

- Custom UI Example: https://github.com/supertokens/supertokens-web-js/tree/master/examples/react/with-thirdpartyemailpassword
- Custom UI Blog post: https://supertokens.medium.com/adding-social-login-to-your-website-with-supertokens-custom-ui-only-5fa4d7ab6402
- Awesome SuperTokens: https://github.com/kohasummons/awesome-supertokens

## Contributing

Please refer to the [CONTRIBUTING.md](https://github.com/supertokens/create-supertokens-app/blob/master/CONTRIBUTING.md) file in the root of the [`create-supertokens-app`](https://github.com/supertokens/create-supertokens-app) repo.

## Contact us

For any questions, or support requests, please email us at [email protected], or join our [Discord](https://supertokens.com/discord) server.

## Authors

Created with :heart: by the folks at SuperTokens.com.
12 changes: 12 additions & 0 deletions boilerplate/backend/node-express/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";

/** @type {import('eslint').Linter.Config[]} */
export default [
{ files: ["**/*.{js,mjs,cjs,ts}"] },
{ languageOptions: { globals: globals.node } },
pluginJs.configs.recommended,
...tseslint.configs.recommended,
{ rules: { "@typescript-eslint/no-require-imports": "off" } },
];
14 changes: 10 additions & 4 deletions boilerplate/backend/node-express/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import cors from "cors";
import supertokens from "supertokens-node";
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import { middleware, errorHandler, SessionRequest } from "supertokens-node/framework/express";
import { getWebsiteDomain, SuperTokensConfig } from "./config";
import { getWebsiteDomain, SuperTokensConfig } from "./config.js";
import Multitenancy from "supertokens-node/recipe/multitenancy";

supertokens.init(SuperTokensConfig);
Expand All @@ -22,9 +22,15 @@ app.use(
// This exposes all the APIs from SuperTokens to the client.
app.use(middleware());

// This endpoint can be accessed regardless of
// having a session with SuperTokens
app.get("/hello", async (_req, res) => {
res.send("hello");
});

// An example API that requires session verification
app.get("/sessioninfo", verifySession(), async (req: SessionRequest, res) => {
let session = req.session;
const session = req.session;
res.send({
sessionHandle: session!.getHandle(),
userId: session!.getUserId(),
Expand All @@ -34,8 +40,8 @@ app.get("/sessioninfo", verifySession(), async (req: SessionRequest, res) => {

// This API is used by the frontend to create the tenants drop down when the app loads.
// Depending on your UX, you can remove this API.
app.get("/tenants", async (req, res) => {
let tenants = await Multitenancy.listAllTenants();
app.get("/tenants", async (_req, res) => {
const tenants = await Multitenancy.listAllTenants();
res.send(tenants);
});

Expand Down
22 changes: 12 additions & 10 deletions boilerplate/backend/node-express/package.json
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
{
"name": "supertokens-node",
"version": "0.0.1",
"type": "module",
"version": "0.0.2",
"private": true,
"description": "",
"main": "index.js",
"main": "dist/index.js",
"scripts": {
"start": "npx ts-node-dev --project ./tsconfig.json ./index.ts"
"start": "npx vite-node ./index.ts",
"lint": "eslint .",
"build": "tsc"
},
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.1",
"helmet": "^5.1.0",
"morgan": "^1.10.0",
"npm-run-all": "^4.1.5",
"express": "^4.21.2",
"supertokens-node": "latest",
"ts-node-dev": "^2.0.0",
"typescript": "^4.7.2"
},
"devDependencies": {
"@eslint/js": "^9.16.0",
"@types/cors": "^2.8.12",
"@types/express": "^4.17.17",
"@types/morgan": "^1.9.3",
"@types/node": "^16.11.38",
"nodemon": "^2.0.16"
"eslint": "^9.16.0",
"globals": "^15.13.0",
"typescript-eslint": "^8.18.0",
"vite-node": "^2.1.8"
},
"keywords": [],
"author": "",
Expand Down
82 changes: 25 additions & 57 deletions boilerplate/backend/node-express/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,62 +1,30 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
"target": "ES2022",
"outDir": "./dist",
"rootDir": "./",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"types": ["node"],
"noEmitOnError": true,

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
"sourceMap": true,

/* Module Resolution Options */
"moduleResolution": "node",
"baseUrl": "./",

/* Additional Checks */
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"include": ["./*.ts"],
"exclude": ["node_modules"]
}
2 changes: 1 addition & 1 deletion lib/build/version.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const package_version = "0.0.55";
export const package_version = "0.0.56";
2 changes: 1 addition & 1 deletion lib/ts/version.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const package_version = "0.0.55";
porcellus marked this conversation as resolved.
Show resolved Hide resolved
export const package_version = "0.0.56";
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "create-supertokens-app",
"type": "module",
"version": "0.0.55",
"version": "0.0.56",
"description": "",
"main": "index.js",
"scripts": {
Expand Down