Basic starter project for a Node.js + Express.js + TypeScript project for starting a new Node.js project using TypeScript.
Basic starter project for any project using Node.js + Express.js + TypeScript. Personally, I'd recommend for small to medium projects, as the imagine with a bigger project, you would need extra folders or structure. However, this template should be malleable enough for a good starting template for most personal projects.
Most of the useful features are for easier configuration, although there are some other packages setup to make it easier for you to start your project without worrying about installing them.
.env.example
, and rename to .env
.env
fileThis project was setup using Node.js v18.5. Please use specified version for best experience.
npm install
npm run dev
Production build is compiled first into JavaScript, built on the ./dist
folder, and can be ran after compilation.
npm run build
npm run start
Every development files are located within the ./src
folder.
app.ts
config
db.ts
controllers
user-controller.ts
middleware
async-middleware.ts
auth-middleware.ts
error-middleware.ts
routes
user-route.ts
__tests__
example.test.ts
types
enums
enums.common.ts
interfaces
interfaces.common.ts
types
types.common.ts
index.d.ts
utils
ApiError.ts
ApiSucess.ts
Passing middleware into the asyncHandler will allow the server to automatically catch any internal server errors, or manually thrown errors from the server.
// ? asyncHandler should be used for every request for easy async handling
export const getUsers = asyncHandler(
async (req: Request, res: Response, next: NextFunction) => {
// Example user, get from database
const user = [{ name: "John Doe" }, { name: "Jaen Doe" }];
// Return json with success message
res.status(200).json(new ApiSuccess<User[]>(user, "Success!"));
},
);
Using ApiError or ApiSuccess allows for consistent responses across all routes; please use this instead of passing your own data structure.
throw new ApiError({}, 500, "Handled by asyncHandler")
res.status(200).json(new ApiSuccess<User[]>(user, "Success!"));
If you add extra folders to this template and would like to use them with aliases, then go through following:
tsconfig.json
{ paths: ... }
(for tsconfig-paths)package.json
{_moduleAliases: ... }
(for production build)