Nuxt.js
This guide provides a comprehensive, step-by-step process to create your first custom widget using Nuxt.js and the TakeProfit Widget SDK (version 0.2.3). By following this guide, you’ll set up a Nuxt.js project, integrate the SDK, configure necessary security headers, and implement basic functionalities to interact with the TakeProfit platform. This example serves as a foundation for building more complex and feature-rich widgets tailored to your specific needs.
Prerequisites
Before you begin, ensure you have the following:
- Node.js: Version 14 or higher. Download from Node.js Official Website.
- npm or Yarn: Package managers that come with Node.js.
- Code Editor: Such as Visual Studio Code.
- Basic Knowledge: Familiarity with JavaScript, Vue.js, and Nuxt.js.
- Access to TakeProfit Platform: For widget integration and testing.
Set Up Your Nuxt.js Project
-
Create a New Nuxt.js App
Use create-nuxt-app to bootstrap a new Nuxt.js project. Open your terminal and run:
Follow the prompts to set up your project. For this guide, it’s recommended to select the following options:
- Choose the package manager:
npm
orYarn
- Choose UI framework:
None
(or your preferred choice) - Choose custom server framework:
None
- Choose Nuxt.js modules: Select based on your preference (e.g.,
Axios
,PWA
) - Choose linting tools: As per your preference
- Choose test framework:
None
(optional) - Choose rendering mode:
Universal (SSR / SSG)
Replace
my-tp-widget
with your desired project name. - Choose the package manager:
-
Navigate to Your Project Directory
-
Start the Development Server
Verify that your Nuxt.js app is set up correctly by starting the development server:
This will run your app at
http://localhost:3000
.
Install the TakeProfit Widget SDK
-
Install the SDK
Integrate the TakeProfit Widget SDK into your Nuxt.js project by installing it via npm or Yarn:
Or with Yarn:
-
Verify Installation
Check your
package.json
to ensuretakeprofit-widget-sdk
is listed underdependencies
:
Configure Nuxt.js Headers for Security
To ensure that your widget can be embedded securely within the TakeProfit platform, you need to configure specific HTTP headers in your Nuxt.js application.
-
Update
nuxt.config.js
Open
nuxt.config.js
and add the following configuration to set the necessary headers: -
Create Server Middleware for Headers
Create a server middleware to set the required HTTP headers.
Open
server-middleware/headers.js
and add the following code:Explanation:
X-Frame-Options
: Controls whether your site can be embedded in an iframe. Setting it toALLOW-FROM https://takeprofit.com
allows the widget to be embedded only from the specified origin.Content-Security-Policy
: Theframe-ancestors
directive specifies valid parents that may embed a page using<frame>
,<iframe>
,<object>
,<embed>
, or<applet>
. Setting it to'self' https://takeprofit.com
allows framing from the same origin and the specified TakeProfit domain.
-
Restart the Development Server
After updating the configurations, restart your development server to apply the changes:
Initialize the SDK in Your Project
-
Create an SDK Initialization Plugin
Nuxt.js allows you to create plugins that can run before the root Vue.js application is instantiated. We’ll create a plugin to initialize the TakeProfit Widget SDK.
Open
plugins/tp-widget-sdk.js
and add the following code: -
Register the Plugin
Open
nuxt.config.js
and register the plugin:Explanation:
mode: 'client'
: Ensures that the plugin is only loaded on the client-side, as the SDK interacts with the browser environment.inject
: Makes the SDK available throughout your application viathis.$tpWidgetSDK
.
-
Define Type Interfaces (Optional)
If you’re using TypeScript, you can define necessary interfaces to enhance type safety. Create
types/tp-widget-sdk.d.ts
:Note: Ensure that your
tsconfig.json
includes thetypes
directory:
Create Your First Widget Page
-
Create the Widget Page
Using Nuxt.js’s file-based routing, create a new page for your widget at
pages/widget.vue
:Explanation:
- Data Property:
menuItemId
stores the ID of the added menu item. - Lifecycle Hooks:
mounted
: Subscribes to widget and channel state changes.beforeDestroy
: Unsubscribes from widget and channel state changes to prevent memory leaks.
- Methods:
handleWidgetChange
: Logs widget state updates.handleChannelChange
: Logs channel state updates.changeSecurity
: Requests a security change and handles the response.addMenuItem
: Adds a new menu item labeled “Refresh Data” and stores its ID.updateMenuItem
: Updates the existing menu item’s label to “Refresh Data (Updated)”.removeMenuItem
: Removes the existing menu item and resetsmenuItemId
.
- Template:
- Buttons to change security and manage menu items.
- Buttons are styled and conditionally disabled based on the presence of
menuItemId
.
- Styles: Scoped CSS for consistent styling.
- Data Property:
-
Ensure Correct Routing
Make sure that navigating to
/widget
in your Nuxt.js app renders thewidget.vue
page. You can test this by visitinghttp://localhost:3000/widget
in your browser.
Manage Widget State and Interactions
-
Handle Widget and Channel State Changes
Ensure that your widget responds to state changes by implementing appropriate handlers within the
widget.vue
component (already demonstrated in Step 5). -
Implement Additional Interactions
Depending on your widget’s requirements, you can add more functionalities such as updating menu items, handling user inputs, and integrating real-time data feeds.
Add Menu Items
Enhance your widget by adding custom menu items to the widget header.
-
Implement Menu Item Functions in
widget.vue
The menu item functions are already implemented in Step 5. Here’s a recap:
-
Add Menu Item
-
Update Menu Item
-
Remove Menu Item
Explanation:
- Add Menu Item: Adds a new menu item labeled “Refresh Data” to the widget header. Upon successful addition, stores the
menuItemId
and enables the update and remove buttons. - Update Menu Item: Updates the existing menu item’s label to “Refresh Data (Updated)”.
- Remove Menu Item: Removes the menu item using the stored
menuItemId
and disables the update and remove buttons.
-
-
Ensure Unique Menu Item IDs
When adding multiple menu items, ensure each has a unique
menuItemId
to prevent conflicts. In this example, we’re managing a single menu item, but you can extend this logic to handle multiple items as needed.
Test Your Widget Locally
-
Start the Development Server
Ensure your Nuxt.js app is running:
The app will be available at
http://localhost:3000
. -
Configure Local Storage for Testing
To simulate the widget’s presence on the TakeProfit platform, configure local storage in your browser:
-
Open the TakeProfit Platform: Navigate to the TakeProfit platform in your browser.
-
Open Developer Console: Press
F12
orCtrl+Shift+I
to open the developer tools. -
Set Local Storage Entry:
Note:
- Replace
'http://localhost:3000/widget'
with your actual widget URL if different. - Provide a valid
imageUrl
for the widget icon.
- Replace
-
-
Reload the TakeProfit Platform
Refresh the TakeProfit platform page. Your Nuxt.js widget should now appear in the widget panel, allowing you to add it to the dashboard and interact with its functionalities.
-
Verify Functionality
- Security Change: Click on the “Set Security” buttons and observe the console logs for successful changes.
- Menu Items: Add the “Refresh Data” menu item and click it to see the corresponding console log. Test updating and removing the menu item to ensure they function as expected.
Deploy Your Widget
Once testing is successful, deploy your widget to a live environment.
-
Choose a Hosting Service
Select a hosting service that can serve Nuxt.js applications and supports custom HTTP headers. Some popular options include:
- Vercel
- Netlify
- AWS Amplify
- Heroku
-
Prepare Your Files for Deployment
Ensure all your files (
pages/widget.vue
,plugins/tp-widget-sdk.js
,server-middleware/headers.js
, etc.) are correctly set up and that your server configuration (server-middleware/headers.js
) is compatible with your hosting service. -
Deploy to Vercel (Example)
Here’s how to deploy your widget to Vercel with the necessary headers:
-
Install Vercel CLI
-
Deploy
Run the deployment command and follow the prompts:
Vercel will automatically detect your Nuxt.js project and handle the build process.
-
-
Configure Headers on Vercel
Vercel allows you to define custom headers using the
vercel.json
configuration file.-
Create
vercel.json
-
Add Header Configuration
Explanation:
src
: Matches all routes.headers
: Sets the required security headers.dest
: Serves the matched route.
-
Deploy with Vercel
Deploy again to apply the new configuration:
-
-
Update Local Storage Configuration
After deployment, update the
iframeUrl
in the TakeProfit platform’s local storage to point to your deployed widget’s URL: -
Final Testing
Reload the TakeProfit platform and verify that your deployed widget functions correctly in the live environment. Test all functionalities, including security changes and menu item interactions, to ensure seamless integration.
Best Practices
-
Secure Communication: Always serve your widget over HTTPS to ensure secure communication with the TakeProfit platform.
-
Unique Identifiers: Ensure that
requestId
andmenuItemId
are unique to prevent conflicts. -
Subscription Management: Always unsubscribe from state changes when they’re no longer needed to prevent memory leaks.
-
Error Handling: Implement robust error handling for all asynchronous operations to enhance user experience.
-
Performance Optimization: Limit the number of active subscriptions and avoid unnecessary state updates to maintain optimal performance.
-
Code Documentation: Keep your code well-documented to facilitate maintenance and future enhancements.
-
Responsive Design: Ensure your widget is responsive and functions seamlessly across different devices and screen sizes.
Next Steps
Congratulations! You’ve successfully created and integrated your first widget using Nuxt.js and the TakeProfit Widget SDK (version 0.2.3). To further enhance your widget, consider the following:
- Explore Advanced SDK Features: Refer to the SDK Reference to utilize all available methods and message types.
- Implement Real-Time Data: Integrate real-time data feeds to provide dynamic and up-to-date information within your widget.
- Customize the UI: Enhance the user interface with additional Vue components and styling to improve user engagement.
- Add More Interactions: Implement more interactive features like custom events, notifications, and user preferences.
- Optimize: Ensure your widget is responsive and functions seamlessly across different devices and screen sizes.
- Security Enhancements: Implement additional security measures to safeguard data and ensure secure communication.
For comprehensive details, refer to the SDK Reference and other documentation resources provided by the TakeProfit Widget SDK.
Troubleshooting
If you encounter issues while setting up or using the TakeProfit Widget SDK, consider the following solutions:
-
SDK Not Connecting
- Check Origins: Ensure that your widget’s domain is allowed and matches the trusted origins (
takeprofit.com
). - Network Issues: Verify that there are no network restrictions or firewall rules blocking communication.
- Check Origins: Ensure that your widget’s domain is allowed and matches the trusted origins (
-
Menu Items Not Appearing
- Local Storage Configuration: Double-check the
iframeUrl
and ensure it points to the correct widget URL. - SDK Initialization: Ensure that
TPWidgetSDK.connect()
andTPWidgetSDK.hideLoader()
are called successfully.
- Local Storage Configuration: Double-check the
-
Security Change Fails
- Valid Security ID: Ensure that the
securityID
you are requesting is valid and recognized by the platform. - Error Handling: Check the console for error messages to understand why the request failed.
- Valid Security ID: Ensure that the
-
Unhandled Promise Rejections
- Implement
.catch
Blocks: Ensure that all asynchronous SDK methods have proper error handling using.catch
to manage rejected promises.
- Implement
-
Performance Issues
- Optimize Subscriptions: Limit the number of active subscriptions and avoid unnecessary state updates.
- Efficient Rendering: Ensure that your Vue components are optimized to prevent unnecessary re-renders.
For persistent issues, refer to the Support and Resources section or contact the support team for assistance.
Additional Resources
- Installation Guide: Detailed instructions for installing the SDK.
- SDK Reference: Comprehensive documentation of all available methods, interfaces, and message types.
- Creating Your First Widget: A practical guide to building and testing a basic widget.
- Nuxt.js Documentation: Official Nuxt.js documentation for deeper understanding.
- Vue.js Documentation: Official Vue.js documentation for building user interfaces.
- JavaScript Documentation: Official JavaScript documentation for deeper understanding.
- Content Security Policy (CSP) Documentation: Learn more about CSP for enhancing security.
- HTTP Headers Documentation: Understand various HTTP headers for better configuration.