what is Subscription in Graphql

what is Subscription  in Graphql

in this atticlas we will explane the what is the Subscription and how to used it and why should used it . ### what is the Subscription in Graphql? Some applications can require a real-time connection to the server to get immediate information...

in this atticlas we will explane the what is the Subscription and how to used it and why should used it .

what is the Subscription in Graphql?

Some applications can require a real-time connection to the server to get immediate information about some events, this can be done with subscriptions in GraphQL actaly use web socket to keep open connection between client and user. When an event is subscribed by a client a steady connection is opened to the server. Whenever that event happens data is pushed to the client from the server. This means that though written in the same syntax as queries and mutations, subscriptions represent a stream of data instead of a request-response-cycle.
look to this shape

thare are keyword used to define Subscription by used type
type Subscription {}
when we used it :
when used do some thing and after then need to notfy this some thing we need to used it
example when user make function as mutation as add and need to notfy it you should used it
in file schema.graphql

  count:Int!

}```
 in file subscription 
 ``` const subscription={
  count:{
    subscribe(parent,args,{pubSub},info){

  let count=0;
  setInterval(() => {
    count++;
  pubSub.publish('count',{
  count
  })
  }, 1000);
  return pubSub.asyncIterator('count')

  }
    }
  }

you should add subscrption in the resolvers file and sould be PubSub from graphql-yog
is the

How to Use Express.js, Node.js and MongoDB.js

How to Use Express.js, Node.js and MongoDB.js

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

Creating a Node Application

To get started I would recommend creating a new database that will contain our application. For this demo I am creating a directory called node-demo. After creating the directory you will need to change into that directory.

mkdir node-demo
cd node-demo

Once we are in the directory we will need to create an application and we can do this by running the command
npm init

This will ask you a series of questions. Here are the answers I gave to the prompts.

The first step is to create a file that will contain our code for our Node.js server.

touch app.js

In our app.js we are going to add the following code to build a very simple Node.js Application.

var express = require("express");
var app = express();
var port = 3000;
 
app.get("/", (req, res) => {
  res.send("Hello World");
});
 
app.listen(port, () => {
  console.log("Server listening on port " + port);
});

What the code does is require the express.js application. It then creates app by calling express. We define our port to be 3000.

The app.use line will listen to requests from the browser and will return the text “Hello World” back to the browser.

The last line actually starts the server and tells it to listen on port 3000.

Installing Express

Our app.js required the Express.js module. We need to install express in order for this to work properly. Go to your terminal and enter this command.

npm install express --save

This command will install the express module into our package.json. The module is installed as a dependency in our package.json as shown below.

To test our application you can go to the terminal and enter the command

node app.js

Open up a browser and navigate to the url http://localhost:3000

You will see the following in your browser

Creating Website to Save Data to MongoDB Database

Instead of showing the text “Hello World” when people view your application, what we want to do is to show a place for user to save data to the database.

We are going to allow users to enter a first name and a last name that we will be saving in the database.

To do this we will need to create a basic HTML file. In your terminal enter the following command to create an index.html file.

touch index.html

In our index.html file we will be creating an input filed where users can input data that they want to have stored in the database. We will also need a button for users to click on that will add the data to the database.

Here is what our index.html file looks like.

<!DOCTYPE html>
<html>
  <head>
    <title>Intro to Node and MongoDB<title>
  <head>

  <body>
    <h1>Into to Node and MongoDB<&#47;h1>
    <form method="post" action="/addname">
      <label>Enter Your Name<&#47;label><br>
      <input type="text" name="firstName" placeholder="Enter first name..." required>
      <input type="text" name="lastName" placeholder="Enter last name..." required>
      <input type="submit" value="Add Name">
    </form>
  <body>
<html>

If you are familiar with HTML, you will not find anything unusual in our code for our index.html file. We are creating a form where users can input their first name and last name and then click an “Add Name” button.

The form will do a post call to the /addname endpoint. We will be talking about endpoints and post later in this tutorial.

Displaying our Website to Users

We were previously displaying the text “Hello World” to users when they visited our website. Now we want to display our html file that we created. To do this we will need to change the app.use line our our app.js file.

We will be using the sendFile command to show the index.html file. We will need to tell the server exactly where to find the index.html file. We can do that by using a node global call __dirname. The __dirname will provide the current directly where the command was run. We will then append the path to our index.html file.

The app.use lines will need to be changed to
app.use("/", (req, res) => {   res.sendFile(__dirname + "/index.html"); });

Once you have saved your app.js file, we can test it by going to terminal and running node app.js

Open your browser and navigate to “http://localhost:3000”. You will see the following

Connecting to the Database

Now we need to add our database to the application. We will be connecting to a MongoDB database. I am assuming that you already have MongoDB installed and running on your computer.

To connect to the MongoDB database we are going to use a module called Mongoose. We will need to install mongoose module just like we did with express. Go to your terminal and enter the following command.
npm install mongoose --save

This will install the mongoose model and add it as a dependency in our package.json.

Connecting to the Database

Now that we have the mongoose module installed, we need to connect to the database in our app.js file. MongoDB, by default, runs on port 27017. You connect to the database by telling it the location of the database and the name of the database.

In our app.js file after the line for the port and before the app.use line, enter the following two lines to get access to mongoose and to connect to the database. For the database, I am going to use “node-demo”.

var mongoose = require("mongoose"); mongoose.Promise = global.Promise; mongoose.connect("mongodb://localhost:27017/node-demo");

Creating a Database Schema

Once the user enters data in the input field and clicks the add button, we want the contents of the input field to be stored in the database. In order to know the format of the data in the database, we need to have a Schema.

For this tutorial, we will need a very simple Schema that has only two fields. I am going to call the field firstName and lastName. The data stored in both fields will be a String.

After connecting to the database in our app.js we need to define our Schema. Here are the lines you need to add to the app.js.
var nameSchema = new mongoose.Schema({   firstName: String,   lastNameName: String });

Once we have built our Schema, we need to create a model from it. I am going to call my model “DataInput”. Here is the line you will add next to create our mode.
var User = mongoose.model("User", nameSchema);

Creating RESTful API

Now that we have a connection to our database, we need to create the mechanism by which data will be added to the database. This is done through our REST API. We will need to create an endpoint that will be used to send data to our server. Once the server receives this data then it will store the data in the database.

An endpoint is a route that our server will be listening to to get data from the browser. We already have one route that we have created already in the application and that is the route that is listening at the endpoint “/” which is the homepage of our application.

HTTP Verbs in a REST API

The communication between the client(the browser) and the server is done through an HTTP verb. The most common HTTP verbs are
GET, PUT, POST, and DELETE.

The following table explains what each HTTP verb does.

HTTP Verb Operation
GET Read
POST Create
PUT Update
DELETE Delete

As you can see from these verbs, they form the basis of CRUD operations that I talked about previously.

Building a CRUD endpoint

If you remember, the form in our index.html file used a post method to call this endpoint. We will now create this endpoint.

In our previous endpoint we used a “GET” http verb to display the index.html file. We are going to do something very similar but instead of using “GET”, we are going to use “POST”. To get started this is what the framework of our endpoint will look like.

app.post("/addname", (req, res) => {
 
});
Express Middleware

To fill out the contents of our endpoint, we want to store the firstName and lastName entered by the user into the database. The values for firstName and lastName are in the body of the request that we send to the server. We want to capture that data, convert it to JSON and store it into the database.

Express.js version 4 removed all middleware. To parse the data in the body we will need to add middleware into our application to provide this functionality. We will be using the body-parser module. We need to install it, so in your terminal window enter the following command.

npm install body-parser --save

Once it is installed, we will need to require this module and configure it. The configuration will allow us to pass the data for firstName and lastName in the body to the server. It can also convert that data into JSON format. This will be handy because we can take this formatted data and save it directly into our database.

To add the body-parser middleware to our application and configure it, we can add the following lines directly after the line that sets our port.

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Saving data to database

Mongoose provides a save function that will take a JSON object and store it in the database. Our body-parser middleware, will convert the user’s input into the JSON format for us.

To save the data into the database, we need to create a new instance of our model that we created early. We will pass into this instance the user’s input. Once we have it then we just need to enter the command “save”.

Mongoose will return a promise on a save to the database. A promise is what is returned when the save to the database completes. This save will either finish successfully or it will fail. A promise provides two methods that will handle both of these scenarios.

If this save to the database was successful it will return to the .then segment of the promise. In this case we want to send text back the user to let them know the data was saved to the database.

If it fails it will return to the .catch segment of the promise. In this case, we want to send text back to the user telling them the data was not saved to the database. It is best practice to also change the statusCode that is returned from the default 200 to a 400. A 400 statusCode signifies that the operation failed.

Now putting all of this together here is what our final endpoint will look like.

app.post("/addname", (req, res) => {
  var myData = new User(req.body);
  myData.save()
    .then(item => {
      res.send("item saved to database");
    })
    .catch(err => {
      res.status(400).send("unable to save to database");
    });
});
Testing our code

Save your code. Go to your terminal and enter the command node app.js to start our server. Open up your browser and navigate to the URL “http://localhost:3000”. You will see our index.html file displayed to you.

Make sure you have mongo running.

Enter your first name and last name in the input fields and then click the “Add Name” button. You should get back text that says the name has been saved to the database like below.

Access to Code

The final version of the code is available in my Github repo. To access the code click here. Thank you for reading !

Vue.js Authentication System with Node.js Backend

Vue.js Authentication System with Node.js Backend

Vue.js Authentication System with Node.js Backend - In this tutorial, we'll explore different authentication types for JavaScript applications and build a Vue authentication system with a Node.js ...

Vue.js Authentication System with Node.js Backend - In this tutorial, we'll explore different authentication types for JavaScript applications and build a Vue authentication system with a Node.js ...

When building a Vue.js authentication system, there are two primary scenarios involved. Scenario one: one party controls both the front-end and back-end; scenario two: a third-party controls the back-end. If it is the latter case, we have to adapt the front-end. It has to deal with whatever authentication type becomes available from the back-end.

The finished code for this tutorial is available at these GitHub repositories:

Front-end JavaScript Authentication Types

In our application, we have the flexibility to choose between various authentication types. This is because we will be in charge of both front-end and back-end. Let us identify the two types. The first one is local or same-domain authentication — this is the case when the front-end and the back-end are both running on the same domain. The second is cross-domain authentication — it is when the front-end and back-end are running on different domains.

These are the two main categories but there are many sub-categories under them. In light of the above, we will use local authentication since we are in charge of the whole system. We will be using many Node.js libraries. But the two main ones are Passport.js and Express.js. Passport.js is an authentication library. It provides several features like local authentication, OAuth authentication and Single Sign-On authentication. Express.js is a server framework for Node.js used for building web applications.

The Application Paradigm

Our application front-end will have two main pages: a login page and a dashboard page. Both authenticated and anonymous users will have access to the login page. The dashboard page will only be accessible to authenticated users. The login page will have a form which will submit data through Ajax to our back-end API. Then, the back-end will check if the credentials are correct and reply back to the front-end with a cookie. This cookie is what the front-end will use to gain access to any locked pages.

Revalidation of the cookie happens on every request to a locked page. If the cookie becomes invalid or the user is not logged in, they cannot access the dashboard. The back-end will send an error response and the front-end will know to redirect the user back to the login page.

We will not be setting up a real database — we will use an array of users in the back-end to mimic some form of a database. Finally, we will have a logout link. This will send a request to our server to invalidate our current session and hence log out the current user.

So, let’s begin building our Vue.js authentication system using Node.js as a back-end.

Vue.js Front-End Setup

To begin with, we first need to have the latest version of Node.js and vue-cli setup. At the time of this article, the latest version of vue-cli is version 3. If the installed version is 2, we want to upgrade — we first need to remove the old version by running:

npm uninstall vue-cli -g


Then install the latest version by running:

npm install -g @vue/cli


followed by

npm install -g @vue/cli-init


After setting up the above, go to any folder in the terminal and run:

vue init webpack vueauthclient


This will create a new application in vueauthclient using the webpack folder organization.

We should get some prompts on the command line. It is safe to select all the defaults — but for this article, we can select “no” for the tests. Next, navigate to this folder using cd vueauthclient and run the application using:

npm run dev


This will launch a development server which is accessible at the URL localhost:8080. After visiting this URL, the Vue.js logo with some text should be visible on the page. The Vue.js component responsible for displaying this page lives in the file:

vueauthclient/src/components/HelloWorld.vue


Main Login Screen

Let us set up our login page. Then, we will change the homepage to default to the login page screen which we are yet to create. From now on, we will leave out the main application folder vueauthclient, when referring to files.

Let us install the Ajax library called Axios using:

npm install axios --save


This is a library which makes it easier to do HTTP Ajax calls to any back-end server. It is available for both front-end and back-end applications but here, we will only use it on the front-end.

Next, create a login component file in src/components/Login.vue. In this file, paste the following:

<template>
    <div>    
        <h2>Login</h2>    
        <form v-on:submit="login">    
            <input type="text" name="email" /><br>    
            <input type="password" name="password" /><br>    
            <input type="submit" value="Login" />    
        </form>    
    </div>
</template>

<script>
    import router from "../router"    
    import axios from "axios"    
    export default {    
        name: "Login",    
        methods: {    
            login: (e) => {    
                e.preventDefault()    
                let email = "[email protected]"   
                let password = "password"    
                let login = () => {    
                    let data = {    
                        email: email,    
                        password: password    
                    }    
                    axios.post("/api/login", data)    
                        .then((response) => {    
                            console.log("Logged in")    
                            router.push("/dashboard")    
                        })    
                        .catch((errors) => {    
                            console.log("Cannot log in")    
                        })    
                }    
                login()    
            }    
        }    
    }
</script>


Let’s break down this code to see what is happening.

The template part below is a form with two input fields: email and password. The form has a submit event handler attached to it. Using the Vue.js syntax v-on:submit="login", this will submit the field data to the login component method.

<template>
    <div>
        <h2>Login</h2>
        <form v-on:submit="login">
            <input type="text" name="email" /><br>
            <input type="password" name="password" /><br>    
            <input type="submit" value="Login" />    
        </form>    
    </div>
</template>


In the script part of the code, as shown below, we are importing our router file. This lives in src/router/index.js. We are also importing the Axios ajax library for the front-end. Then, we are storing the user credentials and making a login request to our back-end server:

<script>
    import router from "../router"        
    import axios from "axios"    
    export default {    
        name: "Login",    
        methods: {    
            login: (e) => {    
                e.preventDefault()   
                let email = "[email protected]"
                let password = "password"
                let login = () => {
                    let data = {
                        email: email,
                        password: password
                    }
                    axios.post("/api/login", data)
                        .then((response) => {
                            console.log("Logged in")
                            router.push("/dashboard")
                        })
                        .catch((errors) => {
                            console.log("Cannot login")
                        })
                }
                login()
            }
        }
    }
</script>


In the script area below,

e.preventDefault()
let email = "[[email protected]](mailto:[email protected])"
let password = "password"


We are storing hard-coded username and password in variables for now. This helps speed up development by preventing us from retyping the same thing. Later, we will switch those out and get the real data from the form submission.

In the final part of the code below, we are making an ajax call using the credentials above. In the case of an ok response from the server, we redirect the user to the dashboard. If the response is not ok, we stay on the same page and log an error in the console.

let login = () => {
  let data = {
    email: email,
    password: password
  }
  axios.post("/api/login", data)
    .then(response => {
      console.log("Logged in")
      router.push("/dashboard")
    })
    .catch(errors => {
      console.log("Cannot login")
    })
}
login()


Now that we have our login component set up, let’s change the router to make sure it recognizes the new page. In the file src/router/index.js, change the existing router to this:

import Vue from "vue"
import Router from "vue-router"
import Login from "@/components/Login"
import HelloWorld from "@/components/HelloWorld"
Vue.use(Router)
export default new Router({
  routes: [
    {
      path: "/",
      name: "HelloWorld",
      component: HelloWorld
    },
    {
      path: "/login",
      name: "Login",
      component: Login
    }
  ]
})


What we’ve done is import our new component, then add an object to the routes array. Remove the HelloWorld route registration, as we won’t be needing it anymore.

Finally, for the login, page, let’s make sure it is the default page of our application. Change the current path of the login route registration from

path: "/login",


to

path: "/",


Don’t forget to delete the route registration for the HelloWorld route or else an error might occur. Navigating to localhost:8080 again in the browser, we should see our new login form. Submitting it at this stage will not do anything except complain that the back-end URL localhost:8080/api/login does not exist.

Setup First Secure Page - The Dashboard

Now onto the dashboard page. Create a component for it by making a file at src/components/Dashboard.vue. In there, paste the following:

<template>
    <div>    
        <h2>Dashboard</h2>    
        <p>Name: {{ user.name }}</p>    
    </div>
</template>
<script>
    import axios from "axios"    
    import router from "../router"    
    export default {    
        name: "Login",    
        data() {    
            return {    
                user: {    
                    name: “Jesse”    
                }    
            }    
        },    
        methods: {    
            getUserData: function() {    
                let self = this    
                axios.get("/api/user")    
                    .then((response) => {    
                        console.log(response)    
                        self.$set(this, "user", response.data.user)    
                    })    
                    .catch((errors) => {    
                        console.log(errors)    
                        router.push("/")    
                    })    
            }    
        },    
        mounted() {    
            this.getUserData()    
        }    
    }
</script>


In the template section, we are displaying the current username. Before setting up the back-end, we will hardcode a user in the front-end. This is so that we can work with this page or else we will get an error.

In the script section, we are importing Axios library and our router. Then, we have a data function for our component where we return an object with a user property. As we can see, we currently have some hardcoded user data.

We also have two methods called getUserData and mounted. The Vue.js engine calls the mounted method when the component has opened. We only have to declare it. The second method, getUserData is called in the mounted method. In there, we are making a call to the back-end server to fetch the data for the currently logged in user.

During the call to the back-end, we get a response from the server. We will have to handle two possible scenarios depending on the response type.

First, if the call was successful, we set the user property with the data returned from the back-end using:

self.$set(this, "user", response.data.user)


Secondly, if there was a login issue, the server responds with an error. Then, the front-end redirects the user back to the login page with this line:

router.push("/")


We use the push method above for redirection and it is available in the package called vue-router, the default router for Vue.js. Let’s add in the route config for this page by adding this to the route file, like we did for the login page. Import the component:

import Dashboard from "@/components/Dashboard"


And add the route definition:

{
    path: "/dashboard",
    name: "Dashboard",
    component: Dashboard
}


Setup Front-End Data Layer with Axios

Now that we have our front-end pages in place, let’s configure Axios and Vue.js. We will make them ready to communicate with our back-end. Because we are in the development phase, the front-end is running on port 8080. Once we start developing our back-end server, it will be running on a different port number 3000. This will be the case until we are ready for production.

There is nothing stopping us from running them on the same port. In fact, will eventually be the case in the end. If we recollect, we are going for the same-domain approach. We will run the back-end and front-end on different ports for now. This is because we want to take advantage of the many useful features of the Vue.js development server. We will touch on how to merge the two (front and back-end) in a later chapter.

Before moving on, let’s highlight one issue here. There is a drawback to developing our application on different ports. It is called Cross-Origin Request Sharing, shortly named CORS. By default, it will not allow us to make cross-domain Ajax requests to our back-end. There is a Node.js library to find a way around that but we will leave that for another tutorial.

The Vue.js development server has something called proxying. It allows our back-end server to think that the front-end is running on the same port as itself. To enable that feature, open up the config file in config/index.js. Under the dev property, add in an object like so:

proxyTable: {

"/api": "http://localhost:3000"

},


In the above code, we are rerouting Ajax requests that begin with /api to the URL [http://localhost:3000](http://localhost:3000 "http://localhost:3000"). Notice that this is different from the URL our front-end application is running on. If we did not have this code, the Ajax requests by default are sent to [http://localhost:8080](http://localhost:8080 "http://localhost:8080"), which is not what we want. When ready for production, we can remove it:

Finally, install the front-end cookie library using:

npm install vue-cookies --save


Securing our Back-End API

Let’s now move onto setting up a Node.js back-end. First of all, we need to have Node.js installed on your system for this part as well. Head over to a terminal window. Create an empty folder called vueauthclient-backend. Navigate to the folder using:

cd vueauthclient-backend


Then initialize a new Node.js application using the command:

npm init


There will be several prompts. Let’s accept the defaults and specify values where required. We should end up with a file called package.json. Create a file called index.js in the project’s root directory. This is where our main code will live. Install several libraries using the command:

npm install --save body-parser cookie-session express passport passport-local


At the top of the index.js file, import the libraries using the code:

const express = require('express')

// creating an express instance
const app = express()
const cookieSession = require('cookie-session')
const bodyParser = require('body-parser')
const passport = require('passport')

// getting the local authentication type
const LocalStrategy = require('passport-local').Strategy


First, let’s initialize the cookie-session and the body-parser libraries using:

app.use(bodyParser.json())

app.use(cookieSession({
    name: 'mysession',
    keys: ['vueauthrandomkey'],
    maxAge: 24 * 60 * 60 * 1000 // 24 hours
}))


We are setting the cookie to expire after 24 hours. Next, let’s instruct our Node.js app that we want to use Passport.js. Do that by adding the line:

app.use(passport.initialize());


Next, tell Passport.js to start its session management system:

app.use(passport.session());


Since we won’t be using a real database for managing users, for brevity’s sake we will use an array for that. Add in the following lines:

let users = [
  {
    id: 1,
    name: "Jude",
    email: "[email protected]",
    password: "password"
  },
  {
    id: 2,
    name: "Emma",
    email: "[email protected]",
    password: "password2"
  }
]


Next, let’s set up the URLs for logging in, logging out and getting user data. These will be found at POST /api/login, GET /api/logout and GET /api/user, respectively. For the login part, paste in the following:

app.post("/api/login", (req, res, next) => {
  passport.authenticate("local", (err, user, info) => {
    if (err) {
      return next(err);
    }

    if (!user) {
      return res.status(400).send([user, "Cannot log in", info]);
    }

    req.login(user, err => {
      res.send("Logged in");
    });
  })(req, res, next);
});


In here, we are instructing Express.js to authenticate the user using the supplied credentials. If an error occurs or if it fails, we return an error message to the front-end. If the user gets logged in, we will respond with a success message. Passport.js handles the checking of credentials. We will set that up shortly. Note that the method passport.authenticate resides in the Passport.js library.

The next URL we will set up is logout. This invalidates our cookie if one exists. Add this to achieve the functionality:

app.get("/api/logout", function(req, res) {
  req.logout();

  console.log("logged out")

  return res.send();
});


Finally, the URL to get the currently logged in users’ data. When logged in, Passport.js adds a user object to the request using the cookie from the front-end as an identifier. We have to use the id from that object to get the required user data from our array of data in the back-end. Paste in the following:

app.get("/api/user", authMiddleware, (req, res) => {
  let user = users.find(user => {
    return user.id === req.session.passport.user
  })

  console.log([user, req.session])

  res.send({ user: user })
})


Notice that, this time, we have a second variable we are passing in before the callback. This is because we want to protect this URL, so we are passing a middleware filter. This filter will check if the current session is valid before allowing the user to proceed with the rest of the operation. Let’s create the middleware using:

const authMiddleware = (req, res, next) => {
  if (!req.isAuthenticated()) {
    res.status(401).send('You are not authenticated')
  } else {
    return next()
  }
}


We have to make sure to declare it before creating the API route for /api/user.

Next, let’s configure Passport.js so it knows how to log us in. After logging in, it will store the user object data in a cookie-session, and retrieve the data on later requests. To configure Passport.js using the local strategy, add in the following:

passport.use(
  new LocalStrategy(
    {
      usernameField: "email",
      passwordField: "password"
    },

    (username, password, done) => {
      let user = users.find((user) => {
        return user.email === username && user.password === password
      })

      if (user) {
        done(null, user)
      } else {
        done(null, false, { message: 'Incorrect username or password'})
      }
    }
  )
)


In here, we are instructing Passport.js to use the LocalStrategy we created above. We are also specifying which fields to expect from the front-end as it needs a username and password. Then, we are using those values to query the user. If these are valid, we call the done callback, which will store the user object in the session. If it is not valid, we will call the done callback with a false value and return with an error. One thing to note is that the above code works in conjunction with the login URL. The call to passport.authenticate in that URL callback triggers the above code.

Next, let’s tell Passport.js how to handle a given user object. This is necessary if we want to do some work before storing it in session. In this case, we only want to store the id as it is enough to identify the user when we extract it from the cookie. Add in the following to achieve that:

passport.serializeUser((user, done) => {
  done(null, user.id)
})


Next, let’s set up the reverse. When a user makes a request for a secured URL. We tell passport how to retrieve the user object from our array of users. It will use the id we stored using the serializeUser method to achieve this. Add this:

passport.deserializeUser((id, done) => {
  let user = users.find((user) => {
    return user.id === id
  })

  done(null, user)
})


Now, let’s add the code which boots up the Node.js server using the following:

app.listen(3000, () => {
  console.log("Example app listening on port 3000")
})


Run the command:

node index.js


This actually starts the server. There will be a message in the console with the text Example app listening on port 3000.

Getting Ready for Production

Now, when we visit the page localhost:8080, we should see a login form. When we submit the form, we get redirected to the dashboard page. We achieve this using the proxy we set up earlier.

This is acceptable for development — but it defeats the purpose of having a same-domain application. To have a same-domain scenario, we need to compile our application for production.

Before that, let’s test that the proxy is working. Comment out the proxy URL code in config/index.js. We may need to restart the development server because we changed a config file.

Now, let’s revisit the login page and submit the form. We will get an error saying that we aren’t allowed access to the back-end server. To get around this, we need to configure our Node.js back-end server. The back-end will now serve our front-end application instead of the development server.

In the console for the front-end, run the command:

npm run build


This will generate all the necessary files needed for production. We can find all the created files from this command in the dist folder. From this point onwards, we have two options: we can either copy this folder over so it is part of our Node.js application or we can tell the Node.js server to refer directly to it on our file system. The latter is useful if we still want them as separate repositories. We will use the latter method.

Navigate to the folder dist. Run the command pwd to get the absolute path of the dist folder, assuming we are on a Linux based system or Mac. If we are on Windows, we can get the absolute path to the folder using an equivalent command.

Copy the absolute path but do not forget to restart the Node.js server after any modification. Since we do not want to keep restarting the server, let’s install nodemon. It can handle that for us when our code changes.

Next, paste in the following after the import statements:

const publicRoot = '/absolute/path/to/dist'

app.use(express.static(publicRoot))


This is telling the server where to look for files.

The final step will be to add a route to the root of our Node.js application. This is so it serves the production-ready code we had compiled. Do that by adding:

app.get("/", (req, res, next) => {
  res.sendFile("index.html", { root: publicRoot })
})


Now, even with the proxy disabled, let’s visit the server root localhost:3000. We will see the login form. Submit this and we should see the dashboard page with the username displayed.

Logout Functionality and Login Data

Note that our application is still using hardcoded data, we want to get that from the submitted form. Change these lines in the login component from:

let email = "[email protected]"

let password = "password"


to:

let email = e.target.elements.email.value

let password = e.target.elements.password.value


Now, we are using the data from the form. Next, let’s set up a link to log us out. In the component src/App.vue, change the template to this:

<template>
    <div id="app">    
        <img src="./assets/logo.png">    
        <div>    
            <router-link :to="{ name: 'Dashboard'}">Dashboard</router-link>    
            <router-link :to="{ name: 'Login'}">Login</router-link>    
            <a href="#" v-on:click="logout">Logout</a>    
        </div>    
        <router-view/>    
    </div>
</template>


Here, we have created links to the login page, the dashboard page, and a logout link. The logout link does not have a corresponding method currently, so let’s create that. In src/App.vue add a logout method in the scripts section:

logout: function (e) {
    axios
      .get("/api/logout")
      .then(() => {
        router.push("/")
      })
}


Here, we are making an Ajax request to the Node.js back-end. Then, we redirect the user to the login page when the response has returned. The logout will not work with our deployed app because we need to redeploy it again for production using:

npm run build


Now, we can revisit the URL localhost:3000. We can log in, log out and visit the dashboard page.

Conclusion

After this tutorial, we should be able to add as many authenticated pages as we want.

If this is the first time using Vue.js, please refer to our introductory blog post here. It will help in setting up and building a basic Vue.js application.

Also, don’t forget to protect you Vue.js application from code theft and reverse engineering. See our handy guide on protecting Vue.js apps with Jscrambler.

*Originally published by Jscrambler at *blog.jscrambler.com

=========================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Nuxt.js - Vue.js on Steroids

☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

☞ Master Vuejs from scratch (incl Vuex, Vue Router)

☞ Vue JS 2.0 - Mastering Web Apps

☞ Vue.js Essentials - 3 Course Bundle

☞ MEVP Stack Vue JS 2 Course: MySQL + Express.js + Vue.js +PHP

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Node.js for Beginners

Learn Node.js from Scratch (Step by Step)

Welcome to my course "Node.js for Beginners - Learn Node.js from Scratch". This course will guide you step by step so that you will learn basics and theory of every part. This course contain hands on example so that you can understand coding in Node.js better. If you have no previous knowledge or experience in Node.js, you will like that the course begins with Node.js basics. otherwise if you have few experience in programming in Node.js, this course can help you learn some new information . This course contain hands on practical examples without neglecting theory and basics. Learn to use Node.js like a professional. This comprehensive course will allow to work on the real world as an expert!
What you’ll learn:

  • Basic Of Node
  • Modules
  • NPM In Node
  • Event
  • Email
  • Uploading File
  • Advance Of Node