ecommerce project
ecommerce project
Project intro. :
1. My rst project is Shopease , which is a full stack ecommerce website designed for seamless
shopping experience
1. Search bar
2. Filter option based on category and price
3. Similar product recommendation feature
4. Braintree payment gateway
Backend :
1. Type 1 : auth wala and related routes
1. Authentication routes ( kind of one time )
• Register
• Login
• Forget password
• Update pro le
2. Product normal
• Create
• delete
• Get all product
• Get single product
• Update product
Frontend :
( things are not in the same order as in the backend but ya here I have made some order follow
this don’t see code directly )
( just for clari cation I have both used bootstrap classes and normal css here )
1. Authentication
• Register
• Login
• Forgot password
2. Extra pages
• About us
• Policy
• Contact us
• Page not found
4. Major pages
fi
fi
ff
1. Home page
• Filter is implemented here
• Pagination + load more
• Product card array to display all product
2. Product detail
( this is the main product page which will open when you click any product in main page )
3. Category page
• simple category use state and display via loop
( there is a hook folder where this use state hook is present nothing imp its just like
a simple function written above )
4. Category product
(exactly same as product page)
• Usage of slug from category where it is rst time clicked ( nav bar link )
• Display all product of that category
5. Cart page
• Context -> auth and cart both used here
• Total price calculation using cart context ( for each person )
• Remove cart in product
• Payment complete code
• Extra : address change code is also written here but leave this
6. Layout
• Navbar
• Footer
• Admin menu
• User menu
( these menu are those dashboard left side link like what I have done is in layout I have
enterer all kind of initial links )
fi
fi
fi
fi
7 . User and admin wrapper
• Adminroute.js
• private.js
( these are used for authorisation and here we have the best use of use e ect which is also
connected to why we made auth as context so that anytime we can access the token in auth and
based on that we can make changes)
( now under this there are multiple nested routes which can only be accessed if this these wrapper
proceeds so here nesting of routes becomes very imp )
• JWT (JSON Web Token) is a compact, self-contained token used to securely transmit
information between a client and a server.
• Explain the structure: header, payload, and signature.
• header has 2 things first is type of token and second is hashing algo used to encrypt it,
hashing algos -> HMAC-SHA256 or RSA
• Payload has user information name, email etc
• To create the signature, you take the encoded header, the encoded payload, a secret key,
and the algorithm specified in the header. The signature ensures that the token hasn’t been
altered.
• The token is signed using a secret key (HMAC) or a public/private key pair (RSA).
• SHA-256 is a cryptographic hash function that outputs a fixed 256-bit hash.
• HMAC is a way to use hash functions (like SHA-256) along with a secret key to verify the
data's integrity and authenticity.
• HMAC : In this method, the same secret key is used to both sign and verify the token.
• RSA (Public/Private Key Pair) : The server uses a private key to sign the token and a
public key to verify it means only the person having private key can sign the token but
public key wale can verify it.
• HMAC is simpler and faster. It’s suitable when only one server is verifying the token. RSA
is useful when you want to share the public key widely without risking the private key.
• Describe how you generate a token upon successful login, send it to the client, and verify it
on every request for protected routes. ( ye to simple flow hai apan samjha denge .. khani
bna ke )
• Discuss how you handle token expiration and what steps are taken to refresh tokens.
• Like JWT token expires after certain time then user can’t verify it and he/she has to login
again .. to avoid this we can use refresh tokens
• When the user successfully logs in (providing valid credentials), the authentication server
generates two token
• An access token: Used to access protected resources (usually has a short lifespan, like
15 minutes to 1 hour).
• A refresh token: Used to obtain a new access token when the current one expires (usually
has a longer lifespan, like days or weeks).
*With JWT u can handle token management and authentication yourself and its simple to use aur
its stateless behavior is key why I used it.
From point 3 :
Filtering :
Q : How did you implement ltering by price and category in your project? -> full ow
Q : How did you optimize performance for ltering with large datasets?
or
Q : How did you handle large datasets during ltering
Ans : wohi intern wale soln -> querying using .limit(), pagination , database me price and category
pe indexing
Q : what if a product belong to mutiple category or say multiple category selected then how
ltering will work ?
Ans : abhi to ye sab nhi socha tha ek hi click hogi category aise hi radio button rakhi hai ..
But simple hai mongodb me category ko univalue ki jagah multivalue array bna do aur ja category
box check ho to multiple values ek array me api se bhejo aur backend pe phele jaise ham
args.category=checked kr rhe the ab args.category = { $in: checked }; use kr lo baki lte and gte
same
Search :
• Product search : they can also ask why didn't u applied ML here or how u can do it using
ML
• This technique focuses on recommending products that are similar to the ones a user has
interacted with (e.g., viewed, added to cart, purchased). You can use product attributes
like category, price, brand, description, etc., to find similarities.
How It Works:
• Feature Extraction: Extract important features from products, such as keywords from the
description, product categories, price ranges, and other metadata.
• Vectorization: Convert these features into vectors using techniques like TF-IDF for text
data or word embeddings (e.g., Word2Vec or BERT).
• Similarity Measure: Use cosine similarity or Euclidean distance to measure the
similarity between products.
• Recommendation: When a user views a product, recommend other products with the
highest similarity scores.
Q : How did you handle scenarios where no search results were found? -> code me dekh lena
Q : what if after search I wan’t to put ltering ab dono kaise handle kroge ?
Ans : inside model. nd({ }) u put any object and make use $and $or $lte $gte $in $notin $eq
ef ciently to ans such question.
Q : what if I write wrong spelling then simple regex will fail ?? How to solve that ??
Ans : phele to say I was making a simple project so did’nt go for advance method used simple
regex Then say I can use Fuzzy matching : its a technique to nd similar words (how)?=> it
calculated the similarity score which is de ned as the min addition or replacement to make the
original word.
For eg. -> boook -> 1 deletion , back -> 2 replacement to make book so using like this it search
Atlas have this implementation of fuzzy matching also elastic search work on same thing and LIKE
in sql came from fuzzy searching
Further u can explain about ML and NLP
Debouncing is a technique used to control the rate at which a function is executed. It ensures that
the function is only triggered once after a speci ed delay, regardless of how many times it is called
fi
fi
fi
fi
fi
fi
within that period. It is used with search bar because a user types multiple time in the search bar and
keep deleting so multiple api request in short period this causes bashad …
How it works :
The debounce function delays the execution of the search query until the user has stopped typing for
a speci c duration (e.g., 300ms). If the user types again before the delay ends, the timer is reset. The
search query is only executed after the delay ends and no further input occurs.
( this will create a bad user experience but it is necessary to balance load in large dataset … like ek
tradeoff hai performace and experience ka )
Throttling is a technique that ensures a function is executed at regular intervals (e.g., every 200ms)
regardless of how frequently it is called. Unlike debouncing, throttling doesn't wait for the user to
stop typing completely. Like user is typing then also the query is triggered if the interval time is
ended …
Throttling is not good for search bars it is good with say in nite scroll like reels etc , because there
u wan’t to make api calls regularly not on the user interaction.
1. Mongo db has exible schema : MongoDB uses a document-oriented data model means it
allows to store things in form of json data , ab iss exibility ka matlab kya hai ->> means tum
ek product ki sari information like category , price , other attributes sab ek hi jagah store kr skte
where in sql due to rigid schema tumhe multiple tables bnani padti now to combine data tumhe
complex joins use krne padte …
2. Second things is again realated to schema itself : in mongo db lets say while de ning schema u
made 3 things for a product but when adding a product a new feature/attribute say colour came
so in mongo db u can directly add this here and these type of usecases are common in ecom.
3. Scalability : MongoDB is horizontally scalable, meaning it can handle large datasets by
distributing data across multiple servers. Does this means SQL is not scalable ?? Ans : no it is
also scalable but
1. SQL databases like MySQL and PostgreSQL are traditionally optimized for vertical scaling,
meaning you improve performance by adding more resources (CPU, RAM, or storage) to a
single server.
2. We can explain this in other way like : SQL databases can scale horizontally, but it’s
complex because of their relational nature
3. Data in SQL databases is often highly interrelated (using JOINs across tables). Distributing
related data across multiple servers (shards) while maintaining the integrity of relationships
can be tricky.
4. Either u need to implement manual sharding
4. Querying in mongodb is easy and intuitive than the complex join in sql .
Ya phir u can say : I designed APIs that allow the frontend to interact with the backend for tasks
like product ltering, cart management, and order placement. While I might not have explicitly
focused on making them RESTful, they align closely with REST principles such as statelessness,
resource orientation, and using HTTP methods appropriately.
Payment gateway :
Q : How did you implement Braintree in your MERN stack project?
1. Braintree has provided us with Braintree SDK ( software developement kit ) which is a library
provided by Braintree to simplify integration with payment gateway , It includes prebuilt
functions and utilities for handling common payment operations like generating client tokens,
creating transactions, and managing refunds means point is sdk sab kr hi rha na
Kaise hota hai process samjhata hun ( code ydd mt krna bss process dekh lo )
Step 1: sabse phele backend ( server side ) pe client token bnta hai , ye one-time hota hai ek baar
payment ke liye
Braintree ki api se hi magte hain ye token
Code :
const braintree = require("braintree");
Step 2: ab ye one time token frontend ko bheja jata hai wo issi se wo payment page jo drop-in-ui
hai wo bna deta hai
Step 3 : ab ek drop-in-ui bn gya ab user isme details dalta hai and submit dabata hai to ab hm ek on
submit eventlistner likhte hain submit button pe jo ek nonce generate krega and this nonce is sent to
backend for further processing of payment
Step 4 : now the nonce recieved is send to Braintree server and wha se msg aata hai result.success
and payment.id ata hai jisse hm payement cnf krte
Step 5 : ab may be payment store krna ho ya order status update krna ho ..
Q :What are the advantages of using Braintree compared to other payment gateways?
Ans : Braintree offers seamless integration for multiple payment methods like PayPal and cards in
one SDK. Its advanced features, such as built-in tokenization, PCI compliance, and webhook
support, make it developer-friendly and secure. Additionally, its sandbox environment and robust
documentation simplify testing and debugging.
Webhooks :
They are automated noti cations sent from one system to another via HTTP when speci c events
occur.
I have not used it but ye ek functionlaity hai Braintree ki
Fayda kya hai webhooks ka : lets say badi company hai to bhot Sara data hoga bhot sari payment
hogi so ek term hoti repeated polling krke means aap baar baar api request bhej rhe ho to check the
payment update but webhook me kya hai .. automated noti cations sent by Braintree to your server
when speci c events occur
So agar interviewer puche ki kaise isse scale kr skte to webhook bta dena ek acha idea hai …
fi
fi
fi
fi
Frontend :
1. Authentication
Register :
• We will take all 6 elds name email pass address answer phone-no. Which we have to sent to
backend as usestate and then simple creating of form and make a submit handler
• For every form e.preventDefault()
• Then same async arrow function and try catch block this format will remain same
• Now using axios with await to send the data and get response in res variable
• Now here I am using toast to show the message came from backend but leave that one more
thing is we are using navigate now to go to login page
Note : in the return react code rstly we have used a helper called layout this layout is just
handling those meta tags for seo so leave this
Note : for creating form simple top div then form tag then inside it take input tags and h3 tags for
their values , inside input tag main things are type , value , onchange , classname , placeholder
and required .
In type we put “text" and in case of email and password we put “email” and “password” as type
only there are multiple other types like number , checkbox, radio ,date etc
then in value we put that variable (usestate wala ) in onchange we put usestate function
Eg. onchange{(e)=>setName(e.target.value)}
Then in classname css class, placeholder what default is written in input tag eg. enter your name
then required.
Note 1 : when ever any kind of data comes from backend it is accessed into the frontend using
res.data then u type your speci c thing res.data.message, res.data.user what ever is sent from
backend
Note 2 : there is one more way to do it you can destructure the data from the res coming from
backend
Login :
• form with just email and password and two button one is forgot password and login
• 2 usestate name and email and auth context hook
• Now again submit handler which will do axios and if we res.data.sucess we will do our setauth
operation
• For all this we need to understand the context hooks rst .. basically they are just usestate only
but declared kind of globally
• Now in auth context is a object with two keys user and token
• From axios we got both user and token value so we will setauth with these updated values
• One note here is our user will always remain login in our case and when new user login old user
token will get replaced into this auth
fi
fi
fi
fi
ff
• Also here we are using local storage for storing token not the cookies or something simple js
code get item set item from local storage
• Navigate and location thing is there but just learn I am navigating to “/“
Context Hooks
Note : rst open these pages -> auth context , search context , cart context to see how context is
written then open index.js to see how the prop drilling happens also login page so that u can
understand the linking between auth context and its usage
return (
<AuthContext.Provider value={[auth, setAuth]}>
{children}
</AuthContext.Provider>
);
};
Simply we put some state variable in a provider function and then return it while passing state and
its function to the children’s
And these children are parameters passed to it
Now one thing is important here in my project I have put a use e ect also with empty dependency
array which will re render and help in persisting the user login ( I will explain it Aage ).
See custom hook is not only for context it can be thought of as any reusable piece of code eg.
say u are handling a form data into multiple state hooks and when button presses u have written a
submit handler to update these state values now all this u can bundle into a say useForm hook
and export this as a custom hook
Now useAuth is your custom hook which u can import on any page.
4 Step 4 : wrapping into provider so that prop drilling can takes place
In my case I have done this in index.js so that complete App is wrapped into the wrapper
But it is not necessary like we can wrap speci c pages also where we want to change our auth
value this enhance the privacy and security.
The children in the auth provider is parameter to it which in our case is App itself
Multiple context hooks in our project : ( all have same format of code )
fi
fi
ff
1. Auth context : this has two things user object ( initially null ) and token ( initially empty string )
and then it is using useE ect and fetching data from local storage and storing.
2. Cart context : it have just cart variable (initially empty array) and a use e ect hook which is
again fetching data of cart from local storage like cart don’t get refreshed after reload (same
thing as above )
3. Search context : it has two things keyword (empty string ) and results (empty array) and this
thing is not fetched from local storage means that useE ect and reload persistence is not here
When u see the login page u will see that there is a setting of auth hook like I am setting the token
there but in the auth context also there is a use e ect hook which is doing the same thing but it is
like taking data from local storage and then setting it to our state .. what is this ?
So this helps in persisting the user when he refreshes the page or closes the browser.
See rstly he will see the login page and enter his credentials and hit submit now the submit
handler at login page is called and it will ask the token and user object from backend as we have
seen then it will store all this into local storage into a “auth” variable which is handling that
multiple user can’t come at the same time thing because key for all is same. Then setting these
values to a custom hook which is our context came from prop drilling from main to app to this
page. Now this is the rst time
Now lets say user have reloaded the page and as we know as reload happens the complete thing
re renders rstly the auth provider will re render then search provider then cart provider and then
App so when this happen my useE ect inside auth context will also run once as there is nothing
in its dependency array and at this time in my local storage res.data is stored and this useE ect is
restoring that from local storage to auth hook.
Forget password:
• Simple three states email, new password and answer and then sending them to backend and
using res.data.sucess just using toast to show message and navigating to login page
• Rest same page as register.
2. Extra pages
• About us
• Policy
• Contact us
• Page not found
Direct return statement nothing else with css classes and direct css
Col-md-6 all these classname based css is part of bootstrap
3. Search
• This is divided into three parts in project search context , search input .js and search .js
• Context is already done
• Search input .js is the main page where search bar is made and we have imported search
context hook here with state as value now as we have seen this search context hook has two
things one is keyword string and second is results array.
• Now on change of search input box I have done this
• onChange={(e) => setValues({ ...values, keyword: e.target.value })}
• Means using spread operator on values means what ever is there just copy and then change
keyword to e.target.value
fi
fi
fi
ff
ff
ff
ff
ff
ff
• Now there is a button near to search bar which is submit button now on click of it we need to
make a submit handler
• Inside this submit handler we are fetching data from api where we will pass our value.keyword
in the url so that it can be accessed using params
• Then it will return array of all products
• Now again spread and updating just to values array no change stop keyword
• Then navigate to /search route which is the next page search.js
const { data } = await axios.get(
`${serverval}api/v1/product/search/${values.keyword}`
);
setValues({ ...values, results: data });
navigate(“/search”);
Note : here we passed the keyword into url using the context (most asked doubt in backend)
Search.js :
• We have been navigated from search input to here as soon as we clicked the search button
• Now here we will use both type of context search and cart
• See the usage of cart is imp .. we have our product cards now we will have a add to cart button
and then on click of it we will update the cart using spread operator and new product also this
will be added to local storage as we have seen our cart items are stored in local storage.
• We can do all this onclick function thing in a separate handler but whi kri diya
• Here there is no logic just react code
• See the usage of ternary operator in return code
• Using values.result.map we are looping over all product and displaying them
• This is similar to what we will do in the main page to display products like do a loop then open
a div rstly put img tag then other h and p tags to display name and description and then a add
to cart and more details button
• There is also one more thing inside more details onclick I am navigating it to product
description page along with p.slug value which could also be p._id . (Imp)
Note : what is kept in the img tag src … so here we are using get photo api and calling our image
by sending p._id
4. Home Page
5. Product detail
• This page contains the main product display and similar product code
• See till now we have seen at backend we can access id from url using req.params and that id is
sent from frontend
fi
fi
• But frontend also have their own url which we de ne at the routes so we can have some id or
slug into these url also and those can be accessed using useparams hook.
• How these params are set into url ? -> see we have displayed products using loop on the main
page so while displaying I know everything about product and as I click on more details button
their so at this time I have product id or slug so which I can pass to this page url and now on
this page I can access this using params , one more eg. is you have multiple category
displayed on nav bar and when u click on the speci c category now think your self how did u
displayed these multiple category name -> manually to nhi likh diya hoga as a good developer
u have asked for all category from backend in a state array and at this time u have all the
information of all category in this array including its id or slug so on click of this category u can
redirect it to some page and pass this id or slug into it url and now on that page u can use this
id or slug to get the exact category value …. Just look at it how good it is
• Now on this page I have few things one is particular product and second is similar product
• So for particular product I just need a object kind of state to store all its details price desc name
etc and for similar product I need a empty state array also when these products are here so
think your self u will also have a add to cart button so ofc u need a cart state (context wala) . So
we have 3 states and 1 use param hook at the top this use param comes similar to other hooks
using react-router-dom
• Now here we have nothing to click as it was in login and register .. so we will use useE ect
hook to use our handler
• 2 handlers we have to get the complete details of this single product and get similar products
• First one requires slug at backend and that slug we will get from param and update this into
product object and simultaneously call similar product function by sending product._id and
product.cateogory._id as parameter here we don’t need any params here because complete
product details I have
• Now similar product handler : simply we have pid and cid call the api and it will give array of
products set them to second similar product state array
• Now display the main product details and everything and here just we have add to cart option
• Again image is done using get photo api by sending the p._id
• Then show similar product use ternary operator on similar product array length and display
them in a loop this code is exactly copied form main page code simple for every add to cart
onclick just update context cart along with spread operator and for every more details onclick
just navigate to this page only and change the slug value in the url
• Note : while displaying currency we get p.price then we have to convert that to Locale string
then choose style as currency and currency as INR to display no. in that formal
Note :
fi
fi
ff