<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nithish Reddy on Medium]]></title>
        <description><![CDATA[Stories by Nithish Reddy on Medium]]></description>
        <link>https://medium.com/@nithishreddy0627?source=rss-43e48bcc16a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dvK8zKEcBY2NrAj4</url>
            <title>Stories by Nithish Reddy on Medium</title>
            <link>https://medium.com/@nithishreddy0627?source=rss-43e48bcc16a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:02:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nithishreddy0627/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building an E-commerce Product Recommender with RAG, LangChain, and Streamlit]]></title>
            <link>https://medium.com/@nithishreddy0627/building-an-e-commerce-product-recommender-with-rag-langchain-and-streamlit-f445ba475119?source=rss-43e48bcc16a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f445ba475119</guid>
            <category><![CDATA[smart-shopping]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[future]]></category>
            <dc:creator><![CDATA[Nithish Reddy]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 00:04:40 GMT</pubDate>
            <atom:updated>2026-07-05T00:04:40.448Z</atom:updated>
            <content:encoded><![CDATA[<p>Building an E commerce Product Recommender with RAG, LangChain, and Streamlit</p><p>Product recommendations are everywhere in online shopping, and they get a lot more interesting when you stop relying on purchase history and start understanding what the user actually means. In this guide, we’ll build a recommendation system that takes a plain English request like “men’s clothing under 1000” and returns real product suggestions using Retrieval Augmented Generation (RAG). By the end, you’ll have a working app that reads a product catalog, understands your query semantically, and returns real products with an LLM.</p><p>See it in action<br>Here’s the experience we’re building toward a search that understands what you mean, then renders real products from the catalog:Semantic product search homepage with filters and product gridType “comfortable running shoes for men” and you get actual running shoes sorted by relevance, not random keyword matches:Semantic search returning real running shoesAsk for a “cotton kurta for summer” and it understands the intent, surfacing the right products:Semantic search returning cotton kurtasNow let’s build it, step by step.</p><p>What we’re building<br>Most recommendation engines use collaborative filtering (“users like you also bought…”) or content based filtering (tag matching). Both need history or exact matches. Ours doesn’t. We’ll use embeddings and a vector store so the app understands meaning, not just keywords, and works even for a brand-new user with no history at all. Here’s the flow:</p><p>Load a Flipkart product catalog (~20,000 products) from CSV.<br>Clean it and pull out the fields we care about.<br>Turn each product into text, embed it, and store it in a FAISS vector database.<br>Let the user type their preferences and get AI-generated recommendations.<br>Prerequisites<br>Before starting, make sure you have:</p><p>Python 3.10 installed.<br>An OpenAI API key.<br>The Flipkart e-commerce dataset in CSV format.<br>Basic familiarity with Python and the command line.<br>Step 1: Set up the project<br>Create a project folder and a virtual environment, then install the dependencies.</p><p>pip install streamlit pandas seaborn matplotlib python-dotenv \<br> faiss-cpu langchain langchain-classic langchain-community \<br> langchain-openai openai tiktoken<br>Step 2: Add your API key<br>Create a .env file in the project root and add your OpenAI key.</p><p>OPENAI_API_KEY=your-api-key<br>This keeps your key out of the code. We’ll load it later with python-dotenv.</p><p>Step 3: Load and clean the data<br>Create a file called data_processing.py. This handles loading the CSV and turning messy raw data into clean, usable columns.</p><p>import pandas as pd<br>import streamlit as st<br>from ast import literal_eval<br><a href="http://twitter.com/st">@st</a>.cache_data<br>def load_data(dataset_path):<br> return pd.read_csv(dataset_path)<br>def extract_primary_category(product_category_tree):<br> try:<br> return literal_eval(product_category_tree)[0].split(‘&gt;&gt;’)[0].strip()<br> except (ValueError, SyntaxError, IndexError):<br> return None<br>The extract_primary_category function is doing the heavy lifting here. The dataset stores categories as a nested string like [“Clothing &gt;&gt; Men’s &gt;&gt; Shirts”], and this line pulls out just the top-level category, Clothing. We also infer a gender field from the product name and description, and keep only the columns we need.</p><p>def preprocess_data(df):<br> df[‘primary_category’] = df[‘product_category_tree’].apply(extract_primary_category)<br> df[‘gender’] = df.apply(<br> lambda x: determine_gender(x[‘product_name’], x[‘description’]), axis=1)<br>columns = [‘pid’, ‘product_url’, ‘product_name’, ‘primary_category’,<br> ‘retail_price’, ‘discounted_price’, ‘description’, ‘brand’, ‘gender’]<br> refined_df = df[columns]<br> refined_df = refined_df.dropna(<br> subset=[‘primary_category’, ‘retail_price’, ‘discounted_price’])<br> return refined_df<br>After this step, our 20,002 raw rows become 19,922 clean rows with no missing values in the important columns.</p><p>Step 4: Build the vector store<br>Now for the interesting part. Create recommendation.py. This is where RAG happens. We take every product, flatten it into a single line of text, and convert that text into embeddings — numerical vectors that capture meaning. Then we store those vectors in FAISS so we can search them fast.</p><p>import os<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_community.document_loaders import DataFrameLoader<br>from langchain_text_splitters import CharacterTextSplitter<br>from langchain_community.vectorstores import FAISS<br>def process_data(refined_df):<br> refined_df[‘combined_info’] = refined_df.apply(lambda row:<br> f”Product Name: {row[‘product_name’]}. Category: {row[‘primary_category’]}. “<br> f”Retail Price: ${row[‘retail_price’]}. Brand: {row[‘brand’]}. “<br> f”Gender: {row[‘gender’]}. Description: {row[‘description’]}”, axis=1)<br>loader = DataFrameLoader(refined_df, page_content_column=”combined_info”)<br> docs = loader.load()<br>text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=200)<br> texts = text_splitter.split_documents(docs)<br>embeddings = OpenAIEmbeddings(openai_api_key=os.getenv(“OPENAI_API_KEY”))<br> vectorstore = FAISS.from_documents(texts, embeddings)<br> return vectorstore<br>Embedding 20,000 products costs API calls and takes a few minutes, so we only want to do it once. Save the vector store to disk and reload it next time.</p><p>def save_vectorstore(vectorstore, directory):<br> vectorstore.save_local(directory)<br>def load_vectorstore(directory, embeddings):<br> return FAISS.load_local(directory, embeddings,<br> allow_dangerous_deserialization=True)<br>Step 5: Generate recommendations<br>With the vector store ready, we connect it to a language model. We give the user four inputs — department, category, brand, and maximum price — and pass them to the LLM through a prompt template.</p><p>from langchain_openai import ChatOpenAI<br>from langchain_classic.chains import LLMChain<br>from langchain_core.prompts import PromptTemplate<br>def display_product_recommendation(refined_df):<br> st.header(“Product Recommendation”)<br>template = “””<br> Kindly suggest three similar products based on the description below:<br> Product Department: {department},<br> Product Category: {category},<br> Product Brand: {brand},<br> Maximum Price range: {price}.<br> “””<br> prompt = PromptTemplate(<br> input_variables=[“department”, “category”, “brand”, “price”],<br> template=template)<br>llm = ChatOpenAI(openai_api_key=os.getenv(“OPENAI_API_KEY”),<br> model_name=’gpt-3.5-turbo’, temperature=0)<br> chain = LLMChain(llm=llm, prompt=prompt)<br>department = st.text_input(“Product Department”)<br> category = st.text_input(“Product Category”)<br> brand = st.text_input(“Product Brand”)<br> price = st.text_input(“Maximum Price Range”)<br>if st.button(“Get Recommendations”):<br> response = chain.run(department=department, category=category,<br> brand=brand, price=price)<br> st.write(response)<br>We set temperature=0 so the model stays focused and consistent instead of getting creative with its suggestions.</p><p>Step 6: Tie it together with Streamlit<br>Finally, create app.py. This is the front door of the application. It loads the data, offers a sidebar menu, and routes the user to either data analysis or recommendations.</p><p>import streamlit as st<br>from data_processing import load_data, preprocess_data, display_data_analysis<br>from recommendation import display_product_recommendation<br>def main():<br> st.title(“E-commerce Product Recommendation”)<br>df = load_data(‘flipkart_com-ecommerce_sample.csv’)<br> if df is not None:<br> refined_df = preprocess_data(df)<br> option = st.sidebar.selectbox(“Select an option”,<br> (“Data Analysis”, “Product Recommendation”))<br> if option == “Data Analysis”:<br> display_data_analysis(refined_df)<br> elif option == “Product Recommendation”:<br> display_product_recommendation(refined_df)<br>if __name__ == ‘__main__’:<br> main()<br>Step 7: Run the app<br>Start the app from your terminal.</p><p>streamlit run app.py<br>Open the URL it gives you, pick “Product Recommendation” from the sidebar, type in what you’re looking for, and click Get Recommendations. The first run builds the vector store, and every run after that loads it instantly from disk.</p><p>A quick note on going further<br>This build is a great starting point, but there’s room to grow. Right now the recommendation button uses the LLM directly, so a natural next step is to wire the FAISS retriever into the answer so every suggestion is grounded in your actual catalog. You could also swap gpt-3.5-turbo for a newer model, add user reviews, or connect it to a live store.</p><p>Conclusion<br>Congratulations! You’ve built an e commerce recommender that understands natural language, searches a product catalog by meaning, and generates suggestions with an LLM all without a single line of collaborative filtering. RAG turns a plain CSV into a smart shopping assistant, and the same pattern works for any catalog you throw at it. Feel free to customize the prompts, dataset, and models to fit your own use case. Thank you for reading, and happy building!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f445ba475119" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building AdRankIQ: A CTR/CVR Prediction and Ad Ranking Platform with XGBoost, PyTorch, and Next.js]]></title>
            <link>https://medium.com/@nithishreddy0627/building-adrankiq-a-ctr-cvr-prediction-and-ad-ranking-platform-with-xgboost-pytorch-and-next-js-98170562c745?source=rss-43e48bcc16a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/98170562c745</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[ads]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[Nithish Reddy]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 15:34:51 GMT</pubDate>
            <atom:updated>2026-07-04T15:34:51.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*VtsEz_SBemw_fuQrKjV96g.png" /></figure><p>In this guide, I will walk you through how I built AdRankIQ, an end to end machine learning platform that predicts Click Through Rate (CTR) and Conversion Rate (CVR) and turns those predictions into smart ad rankings. I hope you have a basic understanding of Python, machine learning, and Next.js before you begin.</p><p>Every ad platform faces the same question: out of thousands of ads, which ones do we actually show? Show the wrong ones and you lose both clicks and revenue. AdRankIQ answers this with two models and a ranking layer, and then presents everything on a live dashboard.</p><p>By the end of this guide, you will have a full ML pipeline that generates data, engineers features, trains CTR and CVR models, ranks items, and displays the results in a Next.js dashboard.</p><h3>Step 1: Set up the project structure</h3><p>Begin by creating a project with two parts: a Python pipeline inside a scripts folder and a Next.js dashboard in the app folder.</p><pre>├── app/                          # Next.js dashboard<br>├── scripts/                      # Python ML pipeline<br>│   ├── generate_dataset.py<br>│   ├── feature_engineering.py<br>│   ├── ctr_models.py<br>│   ├── cvr_models.py<br>│   ├── multi_task_learning.py<br>│   ├── ranking_system.py<br>│   └── run_complete_pipeline.py<br>└── components/                   # Shared UI components</pre><p>Keeping the ML pipeline and the dashboard separate makes each side easier to run and reason about.</p><h3>Step 2: Install the dependencies</h3><p>Next, install the Python libraries for the modeling side.</p><pre>pip install xgboost torch scikit-learn pandas numpy matplotlib seaborn imbalanced-learn aiohttp redis</pre><p>Then install the Node dependencies for the dashboard.</p><pre>npm install</pre><h3>Step 3: Generate a large-scale dataset</h3><p>Since we do not have access to real ad-serving logs, we generate a synthetic dataset. Create generate_dataset.py and build user, item, and contextual features. Set a random seed so your results are reproducible.</p><pre>def generate_large_scale_dataset(n_samples=10_000_000):<br>    np.random.seed(42)<br>    random.seed(42)</pre><pre>    # User features<br>    user_ages = np.random.normal(35, 12, n_samples).clip(18, 80).astype(int)<br>    user_device_types = np.random.choice(<br>        [&#39;mobile&#39;, &#39;desktop&#39;, &#39;tablet&#39;], n_samples, p=[0.65, 0.25, 0.1]<br>    )</pre><pre>    # Item features<br>    item_categories = np.random.choice(<br>        [&#39;electronics&#39;, &#39;fashion&#39;, &#39;home&#39;, &#39;books&#39;, &#39;sports&#39;, &#39;beauty&#39;],<br>        n_samples, p=[0.2, 0.25, 0.15, 0.1, 0.15, 0.15]<br>    )<br>    item_prices = np.random.lognormal(3, 1, n_samples).clip(1, 1000)</pre><p>Notice that the click and conversion labels are not random. They depend on the features, so the models actually have signal to learn from.</p><h3>Step 4: Engineer the features</h3><p>Raw columns are rarely enough. Create feature_engineering.py with a FeatureEngineer class that turns raw signals into 100+ derived features across four groups: user, item, context, and interaction features.</p><h3>Step 5: Train the CTR models</h3><p>Now train the models that predict whether a user will click. Create ctr_models.py and start with an XGBoost model, which is fast and strong on tabular data.</p><pre>class CTRXGBoostModel:<br>    def __init__(self, params=None):<br>        self.default_params = {<br>            &#39;objective&#39;: &#39;binary:logistic&#39;,<br>            &#39;eval_metric&#39;: &#39;auc&#39;,<br>            &#39;max_depth&#39;: 8,<br>            &#39;learning_rate&#39;: 0.1,<br>            &#39;subsample&#39;: 0.8,<br>            &#39;colsample_bytree&#39;: 0.8,<br>            &#39;random_state&#39;: 42,<br>            &#39;n_jobs&#39;: -1<br>        }<br>        self.params = params if params else self.default_params</pre><p>Next, add a PyTorch neural network as a second model, so you can compare a gradient-boosted approach against a deep-learning one.</p><h3>Step 6: Train the CVR models</h3><p>A click is only half the story. Now predict whether a click becomes a conversion. Conversions are rare, so handle the imbalance with SMOTE oversampling, focal loss, and balanced class weighting.</p><h3>Step 7: Combine the tasks with multi-task learning</h3><p>Create multi_task_learning.py with a network that has shared bottom layers and separate heads for CTR and CVR. The shared layers learn a common representation, while each head specializes.</p><h3>Step 8: Rank the ads with business logic</h3><p>Prediction is not the goal. Ranking is. In ranking_system.py, combine the model scores with business rules:</p><pre>final_score = alpha * ctr * cvr * price \<br>            + beta * diversity_bonus \<br>            + gamma * freshness_score</pre><p>Multiplying CTR, CVR, and price ties the ranking to expected revenue, while the diversity and freshness terms keep the results from becoming repetitive.</p><h3>Step 9: Run the complete pipeline</h3><pre>python scripts/run_complete_pipeline.py</pre><p>On the synthetic dataset, the models reach around 0.92 AUC for CTR and 0.89 AUC for CVR. Please treat these as illustrative demo numbers, not production results.</p><h3>Step 10: Visualize the results in the dashboard</h3><pre>npm run dev</pre><p>Open http://localhost:3000. The dashboard has Overview, Model Performance, Ranking Results, and A/B Tests tabs. In the sample A/B test, the improved ranking produced about a 7.6% lift in CTR, a 7.7% lift in CVR, and a 10.4% lift in revenue per user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJgqKA0jwh8ighf3J-zYqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LUC_4S2UBgLNxrjhOLnuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYqWWheVhrgPbRQt0kw4ig.png" /></figure><h3>In conclusion</h3><p>In this guide, we have walked through building AdRankIQ from the ground up. The biggest lesson for me was that raw prediction accuracy is only the starting point. The real value lives in the ranking layer, where you trade off relevance against revenue.</p><p>You can find the full code and screenshots on my <a href="https://github.com/nithishreddy27/AdRankIQ">GitHub</a>.</p><p>Thank You…</p><p>#MachineLearning #DataScience #XGBoost #PyTorch #NextJS</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98170562c745" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Image Scraping with Python and Selenium]]></title>
            <link>https://medium.com/@nithishreddy0627/a-beginners-guide-to-image-scraping-with-python-and-selenium-38ec419be5ff?source=rss-43e48bcc16a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/38ec419be5ff</guid>
            <category><![CDATA[selenium-webdriver]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dataset-for-ml]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nithish Reddy]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 18:01:56 GMT</pubDate>
            <atom:updated>2024-01-31T18:01:56.992Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction:</strong> Web scraping is a powerful technique for extracting information from websites, and it becomes even more interesting when dealing with images. In this tutorial, we’ll explore how to perform image scraping using Python and Selenium, a web automation tool. By the end of this guide, you’ll have the skills to collect images from a website efficiently.</p><p><strong>Prerequisites:</strong></p><ul><li>Python (<a href="https://www.python.org/">https://www.python.org/</a>)</li><li>Selenium (install using pip install selenium)</li><li>A compatible web driver (like ChromeDriver or GeckoDriver)</li></ul><p>To download ChromeDriver, check the version of your Chrome browser by clicking on the three vertical dots, then selecting ‘Help’ and navigating to ‘About Google Chrome’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*xN1MoNJ4Cjg811njY8HrQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*vEz_UDOanYKGYeZ5iSNRHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*r4UBMIk8J_Am08Z0OjUbkg.png" /></figure><p>Now, visit this link and download the closest matching version.<br><a href="https://chromedriver.chromium.org/downloads">https://chromedriver.chromium.org/downloads</a><br>For latest versions of chrome visit <a href="https://googlechromelabs.github.io/chrome-for-testing/">https://googlechromelabs.github.io/chrome-for-testing/</a></p><p>Since my version of chrome is 121.0.6167.140, I have downloaded nearest version to it i.e. 121.0.6167.85 version.</p><p>After downloading, extract the folder and navigate inside. Look for the ‘chrome.exe’ file.</p><p>Now copy the folder path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knkWX3_MmsQTsx7Fh69Fmg.png" /></figure><p>Now, open the Windows menu and type ‘Edit Environment Variables’</p><p>Click on path and choose ‘Edit’ Option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*-XoR9zJ2fCEv4rIipUNYeg.png" /></figure><p>Click on ‘New’ and paste the path that we previously copied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/1*hHrRJHlo4C52a1CxWsjQdA.png" /></figure><p>In my case , it is ‘C:\Users\keert\Downloads\chrome-win64\chrome-win64’</p><p>Click on Ok and close the window.</p><p>Now, open any Python development environment such as PyCharm, Spyder, etc.</p><p>Install the required packages</p><pre>pip install requests selenium</pre><p>Create a new file and enter the code</p><pre>from selenium import webdriver<br>import os<br>import requests<br>from selenium.webdriver.common.by import By<br>from selenium.webdriver.support.ui import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br><br># Set up the web driver (make sure to download the appropriate driver for your browser)<br>driver = webdriver.Chrome()<br><br>def scrape_images(query, num_images, save_path):<br>    # Create a Google Images search URL<br>    search_url = f&quot;https://www.google.com/search?q={query}&amp;tbm=isch&quot;<br><br>    # Open the Google Images search page<br>    driver.get(search_url)<br><br>    # Scroll down to load more images<br>    for _ in range(num_images // 50):<br>        driver.execute_script(&quot;window.scrollBy(0,10000)&quot;)<br><br>    # Wait for the images to load<br>    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, &quot;img.Q4LuWd&quot;)))<br><br>    # Get image elements<br>    img_elements = driver.find_elements(By.CSS_SELECTOR, &quot;img.Q4LuWd&quot;)<br><br>    # Create the save directory on the desktop<br>    desktop_path = os.path.join(os.path.expanduser(&quot;~&quot;), &quot;Desktop&quot;)<br>    save_path = os.path.join(desktop_path, save_path)<br>    os.makedirs(save_path, exist_ok=True)<br><br>    # Loop through the first num_images images<br>    for i, img_element in enumerate(img_elements[:num_images]):<br>        try:<br>            # Click on each image to open it<br>            img_element.click()<br><br>            # Wait for the opened image to load<br>            WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, &#39;img.sFlh5c.pT0Scc.iPVvYb&#39;)))<br><br>            # Get the URL of the opened image<br>            img_url_element = driver.find_element(By.CSS_SELECTOR, &#39;img.sFlh5c.pT0Scc.iPVvYb&#39;)<br>            img_url = img_url_element.get_attribute(&quot;src&quot;)<br><br>            # Download the image<br>            img_name = f&quot;{query}_{i+1}.jpg&quot;<br>            img_path = os.path.join(save_path, img_name)<br>            response = requests.get(img_url, stream=True)<br>            with open(img_path, &#39;wb&#39;) as file:<br>                for chunk in response.iter_content(chunk_size=1024):<br>                    if chunk:<br>                        file.write(chunk)<br>            print(f&quot;Image {i+1} downloaded successfully&quot;)<br><br>        except Exception as e:<br>            print(f&quot;Failed to download image {i+1}: {e}&quot;)<br><br># Example usage<br>query = &quot;dogs&quot;<br>num_images = 10<br>save_path = &quot;downloaded_images&quot;<br>scrape_images(query, num_images, save_path)<br><br># Close the browser<br>driver.quit()</pre><p>This line (By.CSS_SELECTOR, &#39;img.Q4LuWd&#39;) is used to retrieve the images inside the Google Chrome search. If you inspect the webpage, you will be able to see the class names of all the images.</p><p><strong>Check your browser and update the css selector in my case it is Q4LuWd</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*3_GlQpUHQcRuA3z5fYV4yA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*qf3QmbHZeOoabC9i5xsLsw.png" /></figure><p>This is (By.CSS_SELECTOR, &#39;img.sFlh5c.pT0Scc.iPVvYb&#39;), used whenever the image is clicked. This selector may change, so it is suggested to update it with the latest selector. You can obtain the updated selector by clicking on the image and inspecting it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stGBH2KvZjKd1aZ-a5lvGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*eR00PQAooaUmh-1F5wKCDw.png" /></figure><p>After updating the values, you can run the program.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWYUFRuRgsuk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWYUFRuRgsuk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWYUFRuRgsuk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/70207e316f94c062e9f1b2aeaa7c91bf/href">https://medium.com/media/70207e316f94c062e9f1b2aeaa7c91bf/href</a></iframe><p><strong>Conclusion:</strong> Congratulations! You’ve successfully scraped images from a google using Python and Selenium. Remember to use this knowledge responsibly and respect the google’s terms of service. Happy scraping!</p><p>Feel free to customize the code according to your specific needs and the structure of the website you’re working with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38ec419be5ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide: Building a Next.js]]></title>
            <link>https://medium.com/@nithishreddy0627/step-by-step-guide-building-a-next-js-63cd5b2bbbf3?source=rss-43e48bcc16a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/63cd5b2bbbf3</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[google-login]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[credentials]]></category>
            <dc:creator><![CDATA[Nithish Reddy]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 13:16:38 GMT</pubDate>
            <atom:updated>2023-09-09T13:16:38.332Z</atom:updated>
            <content:encoded><![CDATA[<h3>Step-by-Step Guide: Building a Next.js App with Google Authentication and Credentials,Next Auth , MongoDB Atlas, and Mongoose.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sKJMPVyBmQ8WMuIAUuaX6w.jpeg" /></figure><blockquote>For a foundational guide on setting up Next.js with MongoDB, be sure to check out this informative article at <a href="https://medium.com/@nithishreddy0627/connecting-your-next-js-project-to-mongodb-atlas-using-mongoose-a-step-by-step-guide-2d2552b5d7ca">https://medium.com/@nithishreddy0627/connecting-your-next-js-project-to-mongodb-atlas-using-mongoose-a-step-by-step-guide-2d2552b5d7ca</a></blockquote><blockquote>If you’re looking for the complete project, you can find it uploaded on GitHub at <a href="https://github.com/nithishreddy27/authentication-google-credientails">https://github.com/nithishreddy27/authentication-google-credientails</a> . For a detailed, step-by-step guide on how to set up and configure this project, please refer to the article.</blockquote><p>I hope you have basic setup of Nextjs with mongodb Atlas.</p><p><strong>Step 1</strong>: Begin by installing the necessary packages using the command</p><p>npm install next-auth axios crypto.</p><p><strong>Step 2:</strong> Access the Google Cloud Console at <a href="https://cloud.google.com/cloud-console">https://cloud.google.com/cloud-console</a>. Log in to your Google Cloud account, and then click on the <strong>console </strong>button located in the upper-right corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*doy8W1ocjtPBq6K2UwWJBQ.png" /><figcaption>Choose Console</figcaption></figure><p><strong>Step 3:</strong> Next, navigate to the top left corner and click on “Projects” in the Google Cloud Console. Then, select “New Project,” provide your desired project name, and click “Create” to initiate the project creation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hh2fttsBo4RV4f8HoYH0LQ.png" /></figure><p>After creating the project, you can now choose the project you just created from the list of projects displayed in the top-left corner.</p><p>Now, in the search bar located at the top, type “OAuth clients” and click on “Credentials.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEO4PGBkK0a7CvT9UaV5ig.png" /></figure><p>After that, navigate to “OAuth consent screen,” where you’ll need to provide basic details such as your app’s name and email address.</p><p>Choose external and click on create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SoH_HPipVJejmXd8jGys6A.png" /></figure><p>The app logo and domain are optional, so you can leave those fields empty if you prefer. Scroll down, add your email address in the “Developer contact information” section, and then click on “Save and Continue.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*5ZaoekSjbum7l5k_H0pqiQ.png" /></figure><p>In the next step, keep the scopes as they are and proceed by clicking on “Save and Continue.”</p><p>Under “Test users,” click on “Add user,” then enter your email address. Afterward, click on “Save and Continue.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*uJzYyOcEiMD0zkkGlfKw5Q.png" /></figure><p>Next go to Credentials Tab and click on create Credentials and select OAuth Client ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYkBySpHbH-5NpCAVFg-7w.png" /></figure><p>Now select Web Application from Application type dropdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*5OCcLscYkgFf6mgzdt2-Hg.png" /></figure><p>Now add Authorised JavaScript origins as<br><a href="http://localhost:3000/">http://localhost:3000</a></p><p>and Authorised redirect URLs as <a href="http://localhost:3000/api/auth/callback/google">http://localhost:3000/api/auth/callback/google</a></p><p>and click on create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*p3UDEzmxN1CD1_t9rg3qmw.png" /></figure><p>In the small window, you will find your Client ID and Client Secret.</p><p>Copy both of them. Now, paste these credentials into your .env file in your Next.js project, using the variable names GOOGLE_CLIENT_ID for the Client ID and GOOGLE_CLIENT_SECRET for the Client Secret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*R4GPKU-q7icfoGm-o2rOdw.png" /></figure><blockquote>.env file contains GOOGLE_CLIENT_ID , GOOGLE_CLIENT_SECRET , DATABASE_URL</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1LWai6FISoxHvDBOZMUxQ.png" /></figure><p><strong>Step 4 : </strong>Open the _app.js file, which is located in the pages directory of your Next.js project, and copy-paste the following code.</p><pre>import &#39;@/styles/globals.css&#39;<br>import { SessionProvider } from &quot;next-auth/react&quot;<br><br>export default function App({ Component,  pageProps: { session, ...pageProps }  }) {<br>  return (<br>    &lt;SessionProvider session={session}&gt;<br>  <br>  &lt;Component {...pageProps} /&gt;<br>  &lt;/SessionProvider&gt;<br>  )<br>}</pre><p><strong>Step 6 :</strong>Create a folder named “Model” outside the “pages” directory in your project. Inside the “Model” folder, create a file named “User.js” and paste the provided code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*tcmsbEa-c5VKdv6cypVscg.png" /></figure><pre>import mongoose from &quot;mongoose&quot;;<br><br>const userSchema = new mongoose.Schema(<br>  {<br>    email: { <br>      type: String, <br>      trim: true, <br>      unique: true <br>    },<br><br>    hash:{<br>      type:String<br>    },<br>    salt:{<br>      type:String<br>    },<br>    profile: {<br>      firstName: {<br>        type: String,<br>        trim: true,<br>      },<br>      lastName: {<br>        type: String,<br>        trim: true,<br>      },<br>      image: {<br>        type: String,<br>        trim: true,<br>      },<br>     <br>    }<br><br>    <br>   <br>  },<br>  { timestamps: true }<br>);<br><br>export default mongoose.models.users || mongoose.model(&quot;users&quot;, userSchema);</pre><p><strong>Step 7: </strong>Inside your project’s “pages/api/auth” directory, create a file named “[…nextauth.js]” and paste the provided code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*jHSyOXQO0bF6vFoXWyFHyA.png" /></figure><pre>import NextAuth from &quot;next-auth&quot;<br>import GithubProvider from &quot;next-auth/providers/github&quot;<br>import GoogleProvider from &quot;next-auth/providers/google&quot;;<br>import CredentialsProvider from &quot;next-auth/providers/credentials&quot;;<br>import crypto from &quot;crypto&quot;;<br>import connectDB from &quot;@/pages/lib/connectDB&quot;;<br>import User from &quot;@/Model/User&quot;;<br><br>export const authOptions = {<br>  // Configure one or more authentication providers<br>  providers: [<br>    GithubProvider({<br>      clientId: process.env.GITHUB_ID,<br>      clientSecret: process.env.GITHUB_SECRET,<br>    }),<br>    GoogleProvider({<br>        clientId: process.env.GOOGLE_CLIENT_ID,<br>        clientSecret: process.env.GOOGLE_CLIENT_SECRET,<br><br>      }),<br>      CredentialsProvider({<br>        // The name to display on the sign in form (e.g. &quot;Sign in with...&quot;)<br>        name: &quot;Credentials&quot;,<br>        // `credentials` is used to generate a form on the sign in page.<br>        // You can specify which fields should be submitted, by adding keys to the `credentials` object.<br>        // e.g. domain, username, password, 2FA token, etc.<br>        // You can pass any HTML attribute to the &lt;input&gt; tag through the object.<br>        credentials: {<br>          username: { label: &quot;Username&quot;, type: &quot;text&quot;, placeholder: &quot;jsmith&quot; },<br>          password: { label: &quot;Password&quot;, type: &quot;password&quot; }<br>        },<br>        authorize: async (credentials) =&gt; {<br>          const { username, password } = credentials;<br>          await connectDB() <br>          const user = await User.findOne({ email: username });<br>          console.log(&quot;username&quot;,user)<br>          <br>          if (!user) {<br>            return Promise.resolve(null);<br>          }<br>          <br>          const inputHash = crypto.pbkdf2Sync(password, user.salt, 1000, 64, &quot;sha512&quot;).toString(&quot;hex&quot;);<br>          if(inputHash == user.hash){<br>            <br>            return Promise.resolve(user);<br>          }<br>          else{<br>            return Promise.resolve(&quot;invalid user&quot;);<br>          }<br>        },<br>      }),<br>    // ...add more providers here<br>  ],<br><br>  callbacks: {<br>    async jwt({ token, account }) {<br>      // Persist the OAuth access_token to the token right after signin<br>      if (account) {<br>        token.accessToken = account.access_token<br>      }<br>      // console.log(&quot;in jwt&quot;,token)<br>      return token<br>    },<br>    async session({ session, token, user }) {<br><br>      // Send properties to the client, like an access_token from a provider.<br>      session.accessToken = token.accessToken<br><br>      return session <br>    },<br>    async signIn({user}) {<br>      console.log(&quot;inside callback&quot;)<br>      await connectDB()<br>      console.log(&quot;connected&quot;,user)<br>      const u = await User.findOne({email:user.email})<br>      console.log(&quot;found&quot;,u) <br>      const email = user.email;<br>      const name = user.name;<br>      if(!u){<br>        const newUser = new User({<br>          email,<br>          profile:{<br>            firstName:name<br>          }<br>        })<br>        await newUser.save();<br>      }<br>      return true<br>    }<br><br>  }<br><br>  <br>}<br><br>export default NextAuth(authOptions)</pre><p><strong>Step 8:</strong> Create a file inside the “pages/auth” directory and name it “signup.js”. Copy and paste the provided code into this file.</p><pre>import React, { useEffect, useState } from &quot;react&quot;;<br>import { useSession, signIn, signOut } from &quot;next-auth/react&quot;;<br>import { useRouter } from &quot;next/dist/client/router&quot;;<br>import axios from &quot;axios&quot;;<br>import Link from &quot;next/link&quot;;<br><br>export default function signup() {<br>  const [username, setUsername] = useState(&quot;&quot;);<br>  const [password, setPassword] = useState(&quot;&quot;);<br>  const [firstName, setFirstName] = useState(&quot;&quot;);<br>  const [lastName, setLastName] = useState(&quot;&quot;);<br>  const [confirmPassword, setConfirmPassword] = useState(&quot;&quot;);<br>  const [error, setError] = useState(&quot;&quot;);<br>  const { data: session } = useSession();<br><br>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br>    if (confirmPassword == password) {<br>      await axios.post(&quot;../api/auth/signup&quot;, {<br>        username,<br>        password,<br>        firstName,<br>        lastName,<br>      });<br><br>      await signIn(&quot;credentials&quot;, {<br>        redirect: false,<br>        username: username,<br>        password,<br>      });<br>    } else {<br>      setError(&quot;password and confirm password does not match&quot;);<br>    }<br>  };<br><br>  return (<br>    &lt;div className=&quot;min-h-screen &quot;&gt;<br>      &lt;div className=&quot;min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8&quot;&gt;<br>        &lt;div className=&quot;max-w-md w-full space-y-8&quot;&gt;<br>          &lt;div&gt;<br>            &lt;h2 className=&quot;mt-6 text-center text-3xl font-extrabold text-gray-900&quot;&gt;<br>              Create a account<br>            &lt;/h2&gt;<br>          &lt;/div&gt;<br>          &lt;form className=&quot;mt-8 space-y-6&quot; onSubmit={handleSubmit}&gt;<br>            &lt;input type=&quot;hidden&quot; name=&quot;remember&quot; value=&quot;true&quot; /&gt;<br>            &lt;div className=&quot;rounded-md shadow-sm -space-y-px&quot;&gt;<br>              &lt;div&gt;<br>                &lt;label htmlFor=&quot;firstName&quot; className=&quot;sr-only&quot;&gt;<br>                  First Name<br>                &lt;/label&gt;<br>                &lt;input<br>                  id=&quot;firstName&quot;<br>                  name=&quot;firstName&quot;<br>                  type=&quot;text&quot;<br>                  // autoComplete=&quot;email&quot;<br>                  required<br>                  value={firstName}<br>                  onChange={(e) =&gt; setFirstName(e.target.value)}<br>                  className=&quot;appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm&quot;<br>                  placeholder=&quot;First Name&quot;<br>                /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label htmlFor=&quot;lastName&quot; className=&quot;sr-only&quot;&gt;<br>                  Email address<br>                &lt;/label&gt;<br>                &lt;input<br>                  id=&quot;lastName&quot;<br>                  name=&quot;lastName&quot;<br>                  type=&quot;text&quot;<br>                  // autoComplete=&quot;email&quot;<br>                  required<br>                  value={lastName}<br>                  onChange={(e) =&gt; setLastName(e.target.value)}<br>                  className=&quot;appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm&quot;<br>                  placeholder=&quot;Last Name&quot;<br>                /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label htmlFor=&quot;email&quot; className=&quot;sr-only&quot;&gt;<br>                  Email address<br>                &lt;/label&gt;<br>                &lt;input<br>                  id=&quot;email&quot;<br>                  name=&quot;Username&quot;<br>                  type=&quot;email&quot;<br>                  autoComplete=&quot;email&quot;<br>                  required<br>                  value={username}<br>                  onChange={(e) =&gt; setUsername(e.target.value)}<br>                  className=&quot;appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm&quot;<br>                  placeholder=&quot;Email address&quot;<br>                /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label htmlFor=&quot;password&quot; className=&quot;sr-only&quot;&gt;<br>                  Password<br>                &lt;/label&gt;<br>                &lt;input<br>                  id=&quot;password&quot;<br>                  name=&quot;password&quot;<br>                  type=&quot;password&quot;<br>                  autoComplete=&quot;current-password&quot;<br>                  required<br>                  value={password}<br>                  onChange={(e) =&gt; setPassword(e.target.value)}<br>                  className=&quot;appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm&quot;<br>                  placeholder=&quot;Password&quot;<br>                /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label htmlFor=&quot;confirmPassword&quot; className=&quot;sr-only&quot;&gt;<br>                  Confirm Password<br>                &lt;/label&gt;<br>                &lt;input<br>                  id=&quot;confirmPassword&quot;<br>                  name=&quot;confirmPassword&quot;<br>                  type=&quot;password&quot;<br>                  autoComplete=&quot;current-password&quot;<br>                  required<br>                  value={confirmPassword}<br>                  onChange={(e) =&gt; setConfirmPassword(e.target.value)}<br>                  className=&quot;appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm&quot;<br>                  placeholder=&quot;Confirm Password&quot;<br>                /&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;button<br>                type=&quot;submit&quot;<br>                className=&quot;group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500&quot;<br>              &gt;<br>                Sign Up<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>            &lt;p className=&quot;text-red-500&quot;&gt;{error}&lt;/p&gt;<br>            &lt;button<br>              onClick={() =&gt; signIn(&quot;google&quot;)}<br>              className=&quot;bg-green-600 text-white rounded p-2 &quot;<br>            &gt;<br>              Sign in google<br>            &lt;/button&gt;<br>            &lt;button<br>              onClick={() =&gt; signOut()}<br>              className=&quot;bg-red-600 text-white rounded p-2 mx-10 &quot;<br>            &gt;<br>              Sign out<br>            &lt;/button&gt;{&quot; &quot;}<br>          &lt;/form&gt;<br>          &lt;Link href=&quot;/auth/LoginPage&quot; className=&quot;underline &quot;&gt;<br>            Already a user ? Login{&quot; &quot;}<br>          &lt;/Link&gt;<br><br>          &lt;div className=&quot;mx-10&quot;&gt;<br>            User Details :{session &amp;&amp; &lt;div&gt;{JSON.stringify(session)}&lt;/div&gt;}<br>            {!session &amp;&amp; &lt;div&gt;Not logged in&lt;/div&gt;}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*JIhDQnVoMRZlz8dZjfPYlw.png" /></figure><p>Step 9: Inside your project’s “pages/api/auth” directory, create a file named “signup.js” and paste the provided code into this file.</p><pre><br><br>import User from &quot;@/Model/User&quot;;<br>import connectDB from &quot;@/pages/lib/connectDB&quot;;<br>import crypto from &quot;crypto&quot;;<br><br>export default async (req, res) =&gt; {<br>    await connectDB()<br>  if (req.method === &#39;POST&#39;) {<br><br>    <br>    const { username,<br>      password,<br>      firstName,<br>      lastName } = req.body;<br>      console.log(username,password,firstName,lastName)<br>      const email = username<br>      const existingUser = await User.findOne({ email });<br>      const salt = crypto.randomBytes(16).toString(&quot;hex&quot;);<br>      const hash = crypto.pbkdf2Sync(password, salt, 1000, 64, &quot;sha512&quot;).toString(&quot;hex&quot;);<br>      if (existingUser) {<br>            return res.status(400).json({ message: &#39;User already exists&#39; });<br>      }<br>      else{<br>        const newUser = new User({ <br>           email, <br>           hash ,<br>           salt,<br>           profile:{<br>            firstName,<br>            lastName}<br>          });<br>        await newUser.save();<br>      }<br><br>    }<br>  return res.status(200).send({done:true})<br>};</pre><blockquote>Please ensure all the pages imported correctly .</blockquote><blockquote>Now can signup either using email and password or using google authentication.</blockquote><p><strong>Step 10</strong>: To handle the login part, create a file in the “pages/auth” directory named “login.js” and paste the provided code into this file.</p><pre>// pages/login.js<br>// pages/login.js<br><br>import { useState } from &#39;react&#39;;<br>import { useRouter } from &#39;next/router&#39;;<br>import { signIn, useSession,signOut, getSession } from &#39;next-auth/react&#39;;<br>import Link from &#39;next/link&#39;;<br><br>const LoginPage = () =&gt; {<br>  const [username, setUsername] = useState(&#39;&#39;);<br>  const [password, setPassword] = useState(&#39;&#39;);<br>  const [error, seterror] = useState(&#39;&#39;)<br>  const router = useRouter();<br>  const { data: session } = useSession();<br><br>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br>    // console.log(&quot;e&quot;,email,password);<br>    // Use NextAuth.js signIn to authenticate the user<br>    const result = await signIn(&#39;credentials&#39;, {<br>      redirect: false, // Prevent NextAuth.js from automatically redirecting<br>      username,<br>      password,<br>    });<br><br>    if (result?.error) {<br>      console.error(&#39;Login error:&#39;, result.error);<br>      return;<br>    }<br><br>    console.log(result);<br>    if(!result?.user){<br>        seterror(&quot;Invalid username and password&quot;)<br>    }<br>    <br>  };<br><br>  return (<br>    &lt;div className=&quot;min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8&quot;&gt;<br>      &lt;div className=&quot;max-w-md w-full space-y-8&quot;&gt;<br>        &lt;div&gt;<br>          &lt;h2 className=&quot;mt-6 text-center text-3xl font-extrabold text-gray-900&quot;&gt;<br>            Log in to your account<br>          &lt;/h2&gt;<br>        &lt;/div&gt;<br>        &lt;form className=&quot;mt-8 space-y-6 mb-5&quot; onSubmit={handleSubmit}&gt;<br>          &lt;input type=&quot;hidden&quot; name=&quot;remember&quot; value=&quot;true&quot; /&gt;<br>          &lt;div className=&quot;rounded-md shadow-sm -space-y-px&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label htmlFor=&quot;email&quot; className=&quot;sr-only&quot;&gt;<br>                Email address<br>              &lt;/label&gt;<br>              &lt;input<br>                id=&quot;email&quot;<br>                name=&quot;Username&quot;<br>                type=&quot;email&quot;<br>                autoComplete=&quot;email&quot;<br>                required<br>                value={username}<br>                onChange={(e) =&gt; setUsername(e.target.value)}<br>                className=&quot;appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm&quot;<br>                placeholder=&quot;Email address&quot;<br>              /&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label htmlFor=&quot;password&quot; className=&quot;sr-only&quot;&gt;<br>                Password<br>              &lt;/label&gt;<br>              &lt;input<br>                id=&quot;password&quot;<br>                name=&quot;password&quot;<br>                type=&quot;password&quot;<br>                autoComplete=&quot;current-password&quot;<br>                required<br>                value={password}<br>                onChange={(e) =&gt; setPassword(e.target.value)}<br>                className=&quot;appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm&quot;<br>                placeholder=&quot;Password&quot;<br>              /&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div className=&quot;flex items-center justify-between&quot;&gt;<br>            &lt;div className=&quot;flex items-center&quot;&gt;<br>              {/* Add &quot;remember me&quot; checkbox if needed */}<br>            &lt;/div&gt;<br><br>            &lt;div className=&quot;text-sm&quot;&gt;<br>              {/* Add &quot;Forgot your password?&quot; link if needed */}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div&gt;<br>            &lt;button<br>              type=&quot;submit&quot;<br>              className=&quot;group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500&quot;<br>            &gt;<br>              Log In<br>            &lt;/button&gt;<br><br>          &lt;/div&gt;<br><br>          &lt;button<br>              onClick={() =&gt; signIn(&quot;google&quot;)}<br>              className=&quot;bg-green-600 text-white rounded p-2 &quot;<br>            &gt;<br>              Sign in google<br>            &lt;/button&gt;<br>            &lt;button<br>              onClick={() =&gt; signOut()}<br>              className=&quot;bg-red-600 text-white rounded p-2 mx-10 &quot;<br>            &gt;<br>              Sign out<br>            &lt;/button&gt;      &lt;/form&gt;<br>      &lt;Link href=&quot;/auth/signup&quot; className=&#39;underline&#39;&gt; New user ? Sign Up&lt;/Link&gt;<br>      <br>      &lt;div&gt;User : {JSON.stringify(session)}&lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default LoginPage;<br><br><br>export async function getServerSideProps(context) {<br>    // Fetch data from external API<br>    const r =  await getSession(context)<br>    console.log(&quot;inside server&quot;,r)<br>    return { props: {  } }<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*klauC9_PUTtgLGH7iTMfmg.png" /></figure><p>Now, you have the option to log in using both your credentials and Google authentication services.</p><p><strong>In conclusion</strong>, this comprehensive guide has walked you through the process of setting up user authentication in your Next.js application, offering two convenient methods for users to sign up and log in. With the ability to use their credentials or the seamless Google authentication service, your application now provides a flexible and secure user experience. By following these steps, you’ve successfully empowered your application with robust user authentication capabilities, enhancing its usability and accessibility.</p><p><strong>Thank You</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63cd5b2bbbf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting Your Next.js Project to MongoDB Atlas Using Mongoose: A Step-by-Step Guide.]]></title>
            <link>https://medium.com/@nithishreddy0627/connecting-your-next-js-project-to-mongodb-atlas-using-mongoose-a-step-by-step-guide-2d2552b5d7ca?source=rss-43e48bcc16a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d2552b5d7ca</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[mongodb-atlas]]></category>
            <dc:creator><![CDATA[Nithish Reddy]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 15:21:19 GMT</pubDate>
            <atom:updated>2023-09-05T15:21:19.084Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*QDJQTVWHeNUhTsTzn_2yGw.jpeg" /></figure><p><strong>Step 1:</strong> Begin by setting up a Next.js project using either</p><p>npx create-next-app@latest or yarn create next-app with the default installation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*qzZBfRTEyGvjVc9ZAlTlNQ.png" /></figure><p><strong>Step 2:</strong> Next, install the Mongoose library using the npm command</p><p>npm install mongoose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*IqD9auFIVVEDaGMF6mPAuw.png" /></figure><p><strong>Step 3:</strong> Log in to your MongoDB Atlas account and copy the connection string, which can be found under “Connect” &gt; “Connecting with MongoDB for VS Code.” You will also need to note the password, which can be located under “Security” &gt; “Database Access.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*e7N3sv39tKZlnXjTgEl1iA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*qx9DODRKeSOiaROVM62izw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*vLq2SVvL8HlTgQU5iq577Q.png" /></figure><p><strong>Step 4:</strong> Create a .env file within your Next.js project and paste the provided code, replacing the placeholders with your actual MongoDB connection string, username, password, and databaseName desired database name.</p><pre> DATABASE_URL = mongodb+srv://username:password@package.2uykwnp.mongodb.net/databaseName?retryWrites=true&amp;w=majority</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*Y0HYfFQTBUoRHn9LKiCOyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XWvCBsdK8bfINh6DT0WzWw.png" /></figure><p><strong>Step 5:</strong> Inside your project, create a lib folder within the pages directory. In this lib folder, create a file named connectDB.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*BBRRtdBfeg_4ygbx040HNw.png" /></figure><p><strong>Step 6:</strong> Insert the provided code into the connectDB.js file.</p><pre>import mongoose from &quot;mongoose&quot;;<br><br>const DATABASE_URL = process.env.DATABASE_URL;<br><br>if (!DATABASE_URL) {<br>  throw new Error(&quot;Please define the DATABASE_URL environment variable inside .env.local&quot;);<br>}<br><br>let cached = global.mongoose;<br><br>if (!cached) {<br>  cached = global.mongoose = { conn: null, promise: null };<br>}<br><br>async function connectDB() {<br>  if (cached.conn) {<br>    return cached.conn;<br>  }<br><br>  if (!cached.promise) {<br>    const opts = {<br>      bufferCommands: false,<br>    };<br><br>    cached.promise = mongoose.connect(DATABASE_URL, opts).then((mongoose) =&gt; {<br>      return mongoose;<br>    });<br>  }<br>  cached.conn = await cached.promise;<br>  return cached.conn;<br>}<br><br>export default connectDB;</pre><p><strong>Step 7:</strong> Now, outside of the pages directory, create a folder named Model to store all your schemas. Within the Model folder, create a file named User.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*JxSmI4RbK1TPSrwBQvFMLw.png" /></figure><p><strong>Step 8:</strong> Copy and paste the provided code into the User.js file, and feel free to customize it as needed.</p><pre>import mongoose from &quot;mongoose&quot;;<br><br>const User = mongoose.Schema(<br>  {<br>    name: String,<br>    age:Number<br>  },<br>  {<br>    timestamps: true,<br>  }<br>);<br><br>export default mongoose.models.User || mongoose.model(&quot;User&quot;, User);</pre><blockquote><strong>Restart the Server</strong></blockquote><p><strong>Step 9</strong>: In the pages directory, specifically in the index.js file, create a form that allows users to input their details for storage.</p><pre>import Head from &#39;next/head&#39;<br><br><br>export default function Home() {<br>  return (<br>    &lt;div&gt;<br><br>      &lt;form action=&quot;./api/data&quot; method=&quot;post&quot;&gt;<br><br>          &lt;label htmlFor=&quot;name&quot;&gt;Enter Name &lt;/label&gt;<br>          &lt;input type=&quot;text&quot; name=&quot;name&quot; id=&quot;name&quot; /&gt;<br><br><br>          &lt;label htmlFor=&quot;age&quot;&gt; Enter Age &lt;/label&gt;<br>          &lt;input type=&quot;text&quot; name=&quot;age&quot; id=&quot;age&quot; /&gt;<br><br>          &lt;input type=&quot;submit&quot; value=&quot;submit&quot; /&gt;<br><br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*2ejtsjCUUEYCP3vR555qqA.png" /></figure><p><strong>Step 10</strong>: Within the pages directory, create a folder named api, and in this folder, create a file named data.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*8q0MKFguh4FVDV-IMidxdg.png" /></figure><p>Step 11: Insert the provided code into the data.js file. This code will handle the connection to MongoDB, and when users enter data and submit the form, a new user will be created in the database.</p><pre>import user from &quot;../../Model/user&quot;;<br>import connectDB from &quot;../lib/connectDB&quot;<br><br>export default async function handler(req, res) {<br>    await connectDB()<br>    <br>    const {name , age } = req.body;<br>    const person = new user({<br>        name:name,<br>        age:age<br>    })<br>    await person.save()<br>    console.log(&quot;inside api&quot;,name , age)<br>    res.status(200).json({ done: true })<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*tWZ3Kuh4TfDwUgOSx9FiWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*SUDwIL9BCtP-WRBNIUW0lA.png" /></figure><p>This step-by-step guide demonstrates how to set up a Next.js project, connect it to MongoDB Atlas using Mongoose, and create a basic form to store user data in the database. Following these steps should help you establish a functional database connection within your Next.js application.</p><p>Thank You…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d2552b5d7ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>