How To Create a Sign Up Serverless with Microfunctions.io

ben sassi mohammed
4 min readNov 21, 2020

so here we are going to make RESTful API’s for user sign-up with JavaScript and MongoDB using jwt(jsonwebtoken) authentication. Since, we know that registering an user in our app is always our primary motive.

Installation @microfunctions/cli

# Install the Microfunctions CLI globally
npm install -g @microfunctions/cli

Generate a signup function

Install the required package

cd signup
signup$ yarn add bcryptjs jsonwebtoken mongoose

bcryptjs : It is used for hashing and comparing the passwords.

mongoose : It is used to connect to our MongoDB database.

jwtwebtoken : JSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object.

Add uri environment variables

file .ENV

DB_URI=mongodb+srv://login:password@cluster0.kppad.mongodb.net/todo?retryWrites=true&w=majority

Adding the database connection

The process of connecting to MongoDB is twofold. We need to create a dynamic way of creating the connection but also make sure to re-use the same connection if it’s available. We’ll start slow.

import { Schema } from 'mongoose';
import mongoose from "mongoose";
mongoose.Promise = global.Promise;
let isConnected;
const connectToDatabase = () => {
if (isConnected) {
console.log(' using existing database connection');
return Promise.resolve();
}
console.log(' using new database connection');
return mongoose.connect(process.env.DB_URI)
.then(db => {
isConnected = db.connections[0].readyState;
});
};

Create a User Type

const userSchema = new Schema(
{
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
salt: {
type: String,
required: true,
},
},
{ timestamps: true }
);
const User = mongoose.model('User', userSchema);

Add signup function

export const signup = async (event, context) => {
const { email, password } = event.data;
const salt = await bcrypt.genSalt();
const passwordHash = await hashPassword(password,salt)
const user = new User({
email,
password:passwordHash,
salt
});
return connectToDatabase().then(async () => {
const userdb= await user.save();
const jwtPayload = {
email: userdb.email,
id: userdb.id.toString()
};
return jwtSign(jwtPayload);
})
};

Local dev test

Prod Deploy

so here we are going to make RESTful API’s for user sign-up with JavaScript and MongoDB using jwt(jsonwebtoken) authentication. Since, we know that registering an user in our app is always our primary motive.

Installation @microfunctions/cli

# Install the Microfunctions CLI globally
npm install -g @microfunctions/cli

Generate a signup function

Install the required package

cd signup
signup$ yarn add bcryptjs jsonwebtoken mongoose
  • bcryptjs : It is used for hashing and comparing the passwords.
  • mongoose : It is used to connect to our MongoDB database.
  • jwtwebtoken : JSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object.

Add uri environment variables

.ENV

DB_URI=mongodb+srv://login:password@cluster0.kppad.mongodb.net/todo?retryWrites=true&w=majority

Adding the database connection

The process of connecting to MongoDB is twofold. We need to create a dynamic way of creating the connection but also make sure to re-use the same connection if it’s available. We’ll start slow.

import { Schema } from 'mongoose';
import mongoose from "mongoose";
mongoose.Promise = global.Promise;
let isConnected;
const connectToDatabase = () => {
if (isConnected) {
console.log(' using existing database connection');
return Promise.resolve();
}
console.log(' using new database connection');
return mongoose.connect(process.env.DB_URI)
.then(db => {
isConnected = db.connections[0].readyState;
});
};

Create a User Type

const userSchema = new Schema(
{
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
salt: {
type: String,
required: true,
},
},
{ timestamps: true }
);
const User = mongoose.model('User', userSchema);

Add signup function

export const signup = async (event, context) => {
const { email, password } = event.data;
const salt = await bcrypt.genSalt();
const passwordHash = await hashPassword(password,salt)
const user = new User({
email,
password:passwordHash,
salt
});
return connectToDatabase().then(async () => {
const userdb= await user.save();
const jwtPayload = {
email: userdb.email,
id: userdb.id.toString()
};
return jwtSign(jwtPayload);
})
};

Local dev test

Prod Deploy

signup$ microfunctions deploy 
⚡ We will scaffold your app in a few seconds..
UPDATE package.json (889 bytes)
url : https://endpoint.microfunctions.io/api/authnamespace00zpq66kwb/signup 🍺
🍷 blog: https://microfunctions.io/blog

Prod test

x-apikey-header

API keys for authorization. An API key is a token that a client provides when making API calls. to get your x-apikey-header,go to detail namespace page

GITHUB REPO : https://github.com/microfunctionsio/signup

Sign up to discover human stories that deepen your understanding of the world.

ben sassi mohammed
ben sassi mohammed

Written by ben sassi mohammed

Architecte API , Microservices , javascript , java , Angular, kubernetes

No responses yet

Write a response